注意事项:
1.在springboot项目中启动一个socketServer,为了防止主次线程的资源竞争,最好是以线程的方式去实现。
2.在springboot中启动这个线程的时候,建议采用@Configuration方式去生成一个bean,方便以后service bean的注入。
package com.sinosoft.cp.socket;import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.sinosoft.cp.util.TypeUtil;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.lang.Lang;
import org.nutz.log.Log;
import org.nutz.log.Logs;import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;public class SocketServer extends Thread{Log log = Logs.get();private volatile boolean running = false;private long receiveTimeDelay = 1000*30;private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();private ExecutorService pool = new ThreadPoolExecutor(5, 200,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());ServerSocket serverSocket = null;Socket socket = null;private Integer port;@Overridepublic void run() {super.run();startServer();}public SocketServer(int port) {this.port=port;}public void startServer() {if (running) {return;}running = true;try {serverSocket = new ServerSocket(port);System.out.println("server started...");while (true) {socket = serverSocket.accept();//程序阻塞,等待客户端的接入managerConnection(socket);}} catch (Exception e) {e.printStackTrace();} finally {try {serverSocket.close();socket.close();pool.shutdown();} catch (Exception e) {e.printStackTrace();}}}/*** 管理服务器与客户端的连接** @param socket*/public void managerConnection(final Socket socket) {//每一个客户端连接都开启一个子线程pool.execute(new Runnable() {Socket s;boolean run = true;long lastReceiveTime = System.currentTimeMillis();private void overThis() {if (run) {run = false;}if (s != null) {try {s.close();} catch (IOException e) {e.printStackTrace();}}}@Overridepublic void run() {while (running && run) {if (System.currentTimeMillis() - lastReceiveTime > receiveTimeDelay) {overThis();} else {DataInputStream reader = null;BufferedWriter writer = null;try {reader = new DataInputStream(new BufferedInputStream(socket.getInputStream()));writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));while (reader.available() > 0) {lastReceiveTime = System.currentTimeMillis();doService(reader, writer);}} catch (IOException e) {e.printStackTrace();overThis();}}}}});}public void doService(DataInputStream reader, BufferedWriter writer) {};}