Socket的简单使用

 
  1. 创建服务端

    public void yesIo() throws IOException {
        System.out.println("socket监听10086");
        new Thread(() -> {
            //创建一个10086端口的监听器
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(10086);
       
                Socket clientSocket = serverSocket.accept();
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
                String request, response;
                while ((request = in.readLine()) != null) {
                    if ("done".equals(request)) {
                        break;
                    }
                    System.out.println(request);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).run();
       
       
    }
    

    该方法在本地的10086端创建了一个服务端,堵塞当前线程等待response(在客户端的角度是resquest),当用户输入done的时候才能结束死听

  2. 客户端

    System.out.println("启动客户端");
    String ip = "localhost";
    Socket socket = new Socket(ip, 10086);
    Writer writer = new OutputStreamWriter(socket.getOutputStream());
    writer.write("Hello From Client");
    writer.flush();
    writer.close();
    

    客户端代码比较简单,创建一个Socket对象,参数给ip与端口,将sockert的输出流赋值,然后flush 即可

    Socket网络编程很有意思,但是也有自身的缺点,例如行为是阻塞式的,在更多情况下,使用netty更好