在Java中,使用Socket編程實現遠程通信主要包括兩個步驟:創建客戶端(Client)和服務器端(Server)。下面是一個簡單的示例,展示了如何使用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");
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String message = reader.readLine();
System.out.println("Received message: " + message);
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream, true);
writer.println("Hello from server!");
socket.close();
serverSocket.close();
}
}
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");
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream, true);
writer.println("Hello from client!");
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String message = reader.readLine();
System.out.println("Received message: " + message);
socket.close();
}
}
在這個示例中,服務器端監聽指定端口(12345),當客戶端連接到服務器時,服務器會讀取客戶端發送的消息,并向客戶端發送一條消息。客戶端連接到服務器后,會向服務器發送一條消息,并接收服務器返回的消息。
要運行這個示例,請首先運行Server類,然后運行Client類。你會看到客戶端和服務器之間的通信輸出。
這只是一個簡單的示例,實際應用中可能需要考慮更多因素,例如多線程處理并發連接、異常處理、加密通信等。