在Java中,使用Socket编程实现双向通信需要创建两个线程,一个用于客户端发送数据,另一个用于服务器接收数据。以下是一个简单的示例,展示了如何使用Java Socket实现双向通信。
- 服务器端代码(Server.java):
import java.io.*; import java.net.*; public class Server { public static void main(String[] args) throws IOException { int port = 12345; ServerSocket serverSocket = new ServerSocket(port); System.out.println("Server is listening on port " + port); Socket socket = serverSocket.accept(); System.out.println("Client connected"); // 创建两个线程,分别用于读取客户端发送的数据和向客户端发送数据 Thread readerThread = new Thread(new ClientReader(socket)); Thread writerThread = new Thread(new ClientWriter(socket)); readerThread.start(); writerThread.start(); } } class ClientReader implements Runnable { private Socket socket; public ClientReader(Socket socket) { this.socket = socket; } @Override public void run() { try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Received from client: " + inputLine); } } catch (IOException e) { e.printStackTrace(); } } } class ClientWriter implements Runnable { private Socket socket; public ClientWriter(Socket socket) { this.socket = socket; } @Override public void run() { try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) { String response; while ((response = "Server response: ".readLine()) != null) { out.println(response); } } catch (IOException e) { e.printStackTrace(); } } }
- 客户端代码(Client.java):
import java.io.*; import java.net.*; public class Client { public static void main(String[] args) throws IOException { String serverAddress = "localhost"; int port = 12345; Socket socket = new Socket(serverAddress, port); System.out.println("Connected to server"); // 创建两个线程,分别用于向服务器发送数据和接收服务器的响应 Thread senderThread = new Thread(new ServerSender(socket)); Thread receiverThread = new Thread(new ServerReceiver(socket)); senderThread.start(); receiverThread.start(); } } class ServerSender implements Runnable { private Socket socket; public ServerSender(Socket socket) { this.socket = socket; } @Override public void run() { try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) { String message; while ((message = "Client message: ".readLine()) != null) { out.println(message); } } catch (IOException e) { e.printStackTrace(); } } } class ServerReceiver implements Runnable { private Socket socket; public ServerReceiver(Socket socket) { this.socket = socket; } @Override public void run() { try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Received from server: " + inputLine); } } catch (IOException e) { e.printStackTrace(); } } }
在这个示例中,服务器监听指定端口(例如12345),当客户端连接到服务器时,服务器会创建两个线程,一个用于读取客户端发送的数据,另一个用于向客户端发送数据。客户端也创建了两个线程,一个用于向服务器发送数据,另一个用于接收服务器的响应。这样,客户端和服务器就可以通过这两个线程实现双向通信。