SpringBoot實現簡單socket服務端


1.啟動類

@SpringBootApplication
public class serverApplication {

    public static void main(String[] args) {

        SpringApplication.run(serverApplication.class, args);

        DemoServer demoServer = new DemoServer();
        try {
            demoServer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

 

2.socket服務實現處理器都在這里

@Component
public class DemoServer {
    
    private static final Logger logger = LoggerFactory.getLogger(DemoServer.class);

    public void start() throws IOException {
        //線程池,有待商榷
        ExecutorService newCacheThreadPool = newCachedThreadPool();
        ServerSocket server = new ServerSocket(30038);
        logger.info("服務啟動...");

        while (true) {
            final Socket socket = server.accept();
            logger.info("開始處理請求");
            newCacheThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        handler(socket);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private static void handler(Socket socket) throws Exception {
        byte[] bytes = new byte[1024];
        try {
            InputStream inputStream = socket.getInputStream();
            StringBuilder sb = new StringBuilder();
            while (true) {
                //讀取數據(阻塞)
                int read = inputStream.read(bytes);
                if (read != -1) {

                    sb.append(new String(bytes, Charset.forName("gbk")));
                    //處理響應
                    String respMsg = new String("return");
                    byte[] respdata = respMsg.getBytes();
                    OutputStream outputStream = socket.getOutputStream();
                    outputStream.write(respdata);

                } else {
                    break;
                }

            }
            logger.info("請求:{}" , sb);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            logger.info("socket關閉");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM