当前位置:   article > 正文

springBoot编写tcp服务端_springboot tcp服务端

springboot tcp服务端
  1. public static void main(String[] args) {
  2. SpringApplication.run(dwdp.class, args);
  3. try {
  4. ServerSocket serverSocket = new ServerSocket(9300);
  5. System.out.println("启动服务器....");
  6. Socket socket = serverSocket.accept();
  7. System.out.println("客户端:"+socket.getInetAddress().getHostAddress()+"已连接到服务器");
  8. BufferedReader br = new BufferedReader((new InputStreamReader(socket.getInputStream())));
  9. CountDownLatch countDownLatch = new CountDownLatch(1);
  10. ThreadUtil.execute(()->{
  11. try{
  12. String msg;
  13. while (true){
  14. msg= br.readLine();
  15. if(StrUtil.isNotEmpty(msg)){
  16. System.out.println("客户端:"+msg);
  17. }
  18. }
  19. }catch (Exception e){
  20. e.printStackTrace();
  21. }
  22. });
  23. ThreadUtil.execute(()->{
  24. try{
  25. while (true){
  26. Scanner scanner = new Scanner(System.in);
  27. String msg =scanner.nextLine();
  28. if(StrUtil.isNotEmpty(msg)){
  29. if(msg=="exit"){
  30. countDownLatch.countDown();
  31. }else{
  32. BufferedWriter bw = new BufferedWriter(new
  33. OutputStreamWriter(socket.getOutputStream()));
  34. bw.write(msg+"\n");
  35. bw.flush();
  36. }
  37. }
  38. }
  39. }catch (Exception e){
  40. }
  41. });
  42. countDownLatch.await();
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. }
  46. }

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/883580
推荐阅读
相关标签
  

闽ICP备14008679号