You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Socket即时读写:实现客户端与服务端乒乓通信需求

Java Socket 乒乓通信实现

Got it, let's build this ping-pong communication step by step. I'll provide both the server and client code, along with straightforward explanations for key parts so you can follow along easily.

服务端代码

The server uses try-with-resources to automatically manage socket resources—this keeps the code clean and avoids accidental resource leaks. It listens for incoming connections, reads the "Hello" message from the client, prints it to the console, and sends the same message back as a response.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class PingPongServer {
    public static void main(String[] args) {
        // 监听端口号,这里用8888,你可以根据需求修改
        int port = 8888;
        
        // Try-with-resources 自动关闭ServerSocket和客户端Socket
        try (ServerSocket serverSocket = new ServerSocket(port);
             Socket clientSocket = serverSocket.accept(); // 阻塞等待客户端连接
             BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true)) {
            
            System.out.println("客户端已成功连接");
            
            // 读取客户端发送的消息
            String clientMessage = in.readLine();
            System.out.println("收到客户端消息: " + clientMessage);
            
            // 向客户端返回"Hello"响应
            out.println("Hello");
            System.out.println("已向客户端返回响应");
            
        } catch (IOException e) {
            System.err.println("服务端运行出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

客户端代码

The client connects to the server, sends the initial "Hello" message, waits for the server's response, prints it to the console, then exits gracefully.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class PingPongClient {
    public static void main(String[] args) {
        // 服务端IP(本地测试用localhost即可)和端口
        String serverIp = "localhost";
        int serverPort = 8888;
        
        try (Socket socket = new Socket(serverIp, serverPort);
             PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
            
            // 向服务端发送"Hello"
            out.println("Hello");
            System.out.println("已向服务端发送消息: Hello");
            
            // 读取服务端的响应
            String serverResponse = in.readLine();
            System.out.println("收到服务端响应: " + serverResponse);
            
        } catch (IOException e) {
            System.err.println("客户端运行出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

运行说明

  1. First, run the PingPongServer class—it will hang and wait for a client to connect.
  2. Then run the PingPongClient class. You'll see the server print the received "Hello" and confirm the response was sent, while the client prints the server's "Hello" response before exiting.

Quick tips:

  • We use BufferedReader and PrintWriter for text-based communication, which handles character encoding and line endings smoothly.
  • The true parameter in PrintWriter enables auto-flush, so messages are sent immediately without needing to call flush() manually.
  • Try-with-resources ensures all sockets and streams are closed automatically, even if an exception pops up.

内容的提问来源于stack exchange,提问作者Saorikido

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:21:17