2020-12-30 09:39阅读: 2045评论: 0推荐: 0

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();
            }
        }
    }

}
复制代码

 

本文作者:zydjjcpdszylddpll

本文链接:https://www.cnblogs.com/jyfs/p/14209872.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   zydjjcpdszylddpll  阅读(2045)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起