JAVASE网络编程之TCP实现聊天通讯

TCPClientDemo01 类,客户端

public class TCPClientDemo01 {
          
   

    public static void main(String[] args) {
          
   
        try {
          
   
            InetAddress name = InetAddress.getByName("127.0.0.1");
            System.out.println(name);
            int port =9999;
            //2.创建一个socket连接
            Socket socket = new Socket(name,port);
            //3.发送消息IO流
            OutputStream os = socket.getOutputStream();
            os.write("你好,欢迎光临!!!".getBytes());
            os.close();
            socket.close();
        } catch (Exception e) {
          
   
            e.printStackTrace();
        }
    }
}

TCPServerDome01 服务端接收

public class TCPServerDome01 {
          
   

    public static void main(String[] args) {
          
   
        //首先要有一个地址
        try {
          
   
            ServerSocket serverSocket = new ServerSocket(9999);
            // 2等待客户端连接过来
            Socket accept = serverSocket.accept();
            //读取客户信息
            InputStream is = accept.getInputStream();
            //使用管道流
            ByteArrayOutputStream boas = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len=is.read(buffer))!=-1){
          
   
                boas.write(buffer,0,len);
            }
            System.out.println(boas.toString());

            boas.close();
            is.close();
            accept.close();
            serverSocket.close();

        } catch (IOException e) {
          
   
            e.printStackTrace();
        }

    }

}
经验分享 程序员 微信小程序 职场和发展