springBoot编写tcp服务端


    public static void main(String[] args) {
        SpringApplication.run(dwdp.class, args);
        try {
            ServerSocket serverSocket = new ServerSocket(9300);
            System.out.println("启动服务器....");
            Socket socket = serverSocket.accept();
            System.out.println("客户端:"+socket.getInetAddress().getHostAddress()+"已连接到服务器");
            BufferedReader br = new BufferedReader((new InputStreamReader(socket.getInputStream())));
            CountDownLatch countDownLatch = new CountDownLatch(1);
            ThreadUtil.execute(()->{
                try{
                    String msg;
                    while (true){
                        msg= br.readLine();
                        if(StrUtil.isNotEmpty(msg)){
                            System.out.println("客户端:"+msg);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            });
            ThreadUtil.execute(()->{
                try{
                    while (true){
                        Scanner scanner = new Scanner(System.in);
                        String msg =scanner.nextLine();
                        if(StrUtil.isNotEmpty(msg)){
                            if(msg=="exit"){
                                countDownLatch.countDown();
                            }else{
                                BufferedWriter bw = new BufferedWriter(new
                                        OutputStreamWriter(socket.getOutputStream()));
                                bw.write(msg+"\n");
                                bw.flush();
                            }
                        }
                    }
                }catch (Exception e){

                }
            });
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

posted @ 2022-08-11 18:49  码海兴辰  阅读(142)  评论(0编辑  收藏  举报