欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java Socket实现TCP客户端服务端

程序员文章站 2022-06-06 16:06:01
...

客户端

notice
发送语句要加换行符来判断语句结束,writer要flush将数据从缓冲区发送到管道

         try {
            Socket socket = new Socket("127.0.0.1", 12340);
            System.out.println("已建立连接");
            OutputStream outputStream = socket.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String send;
            while ((send = reader.readLine()) != null) {
                writer.write(send+'\n');
                writer.flush();   
                System.out.println("已发送消息");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

服务端

        ServerSocket server = new ServerSocket(12340);
        try {
            Socket socket = server.accept();
            System.out.println("已建立连接" + socket.getRemoteSocketAddress());
            InputStream inputStream = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String str = "";
            while ((str = reader.readLine()) != null) {
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }