在Java中,使用Socket編程實現雙向通信需要創建兩個線程,一個用于客戶端發送數據,另一個用于服務器接收數據。以下是一個簡單的示例,展示了如何使用Java Socket實現雙向通信。
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();
}
}
}
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),當客戶端連接到服務器時,服務器會創建兩個線程,一個用于讀取客戶端發送的數據,另一個用于向客戶端發送數據。客戶端也創建了兩個線程,一個用于向服務器發送數據,另一個用于接收服務器的響應。這樣,客戶端和服務器就可以通過這兩個線程實現雙向通信。