Tcp实现聊天

public class TcpServerDemo01 {
    public static void main(String[] args) throws IOException {
        //1.我得有一个地址
        ServerSocket serverSocket = new ServerSocket(9999);
        //2待客户端连接
        Socket socket = serverSocket.accept();
        //3.读取客户端时消息
        InputStream is = socket.getInputStream();
        //管道流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while((len=is.read(buffer))!=-1){
            baos.write(buffer,0,len);
        }
        System.out.println(baos.toString());
        baos.close();
        socket.close();
    }

}

先启动服务端

public class TcpClientDemo01 {
    public static void main(String[] args) throws IOException {
        //1.要知道服务器的地址、端口号
        InetAddress serverIP = InetAddress.getByName("127.0.0.1");
        int port = 9999;
        //2.创建一个socket连接
        Socket socket = new Socket(serverIP,port);
        //3.发送消息IO流
        OutputStream os = socket.getOutputStream();

        os.write("你好欢迎学习".getBytes());
        os.close();
        socket.close();
    }

}

再启动客户端

客户端

1.连接服务器Socket

2.发送消息

服务端

1.建立服务的端口ServerSocket

2.等待用户的连接accept

3.接收用户的消息

你可能感兴趣的:(tcp/ip,java,网络)