tcp实现聊天

客户端

 1 public class A {
 2     public static void main(String[] args) throws IOException {
 3         String guo="你好啊";
 4        int port=8888;
 5         Socket socket = null;
 6         InetAddress ip = InetAddress.getByName("127.0.0.1");
 7         socket=new Socket(ip,port);
 8         OutputStream outputStream = socket.getOutputStream();
 9         outputStream.write(guo.getBytes());
10         socket.close();
11         outputStream.flush();
12         outputStream.close();
13 
14     }
15 }

服务器端

public class B {
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(8888);
        Socket socket = serverSocket.accept();
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int len;
        while ((len=inputStream.read(bytes))!=-1){
            byteArrayOutputStream.write(bytes,0,len);
    }
        System.out.println(byteArrayOutputStream.toString());
        socket.close();
        inputStream.close();
        byteArrayOutputStream.flush();
        byteArrayOutputStream.close();
    }
}

 

posted on 2023-03-17 10:46  大风吹过12138  阅读(20)  评论(0)    收藏  举报

导航