java Socket 网络编程建立简单的长链接

建立socke   

 

       public void server() {
     ServerSocket serverSocket
= null; try { serverSocket = new ServerSocket(9898); //端口号 //通过死循环开启长连接,开启线程去处理消息 System.out.println("服务启动..."); while (true) { Socket socket = serverSocket.accept();//接受客户端的连接 (阻塞处理) new Thread(new MyRuns(socket)).start();//接收到客户端的消息,创建线程去处理 } } catch (Exception e) { e.printStackTrace(); } finally { try { if (serverSocket != null) { serverSocket.close();//记得关闭连接哦! } } catch (Exception e2) { e2.printStackTrace(); } } }





 public class MyRuns implements Runnable {
     Socket socket;
        BufferedReader reader;
        BufferedWriter writer;
        public MyRuns(Socket socket) {
            super();
            this.socket = socket;
        }
        public void run() {
            Map<String, String> res = new HashMap<>();
            try {
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));//读取客户端消息
                writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));//向客户端写消息
                String mess = reader.readLine();
                System.out.println("接收的信息为:" + mess);
                if (mess != null && !"".equals(mess)) {
                    Map<String, Object> readValue = JSONObject.parseObject(mess, Map.class);
                    System.out.println(readValue.toString());
                    String XXX= readValue.get("XXX").toString();
                    res.put("res", true);
                }
            } catch (Exception e) {
                e.printStackTrace();
                res.put("res", String.valueOf(false));
                res.put("msg", e.toString());
            } finally {
                try {
                    System.out.println("运行结果:" + res);
                    writer.write(JSONObject.toJSONString(res));
                    writer.flush();
                    if (reader != null) {
                        reader.close();
                    }
                    if (writer != null) {
                        writer.close();
                    }
                    if (socket != null) {
                        socket.close();
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }

 

进行连接测试

客户端(三种方式:自己写的客户端、NetAssist、SocketTest)


 

posted @ 2022-07-06 10:08  爱吃猫的鱼摆摆  阅读(976)  评论(0编辑  收藏  举报