Java Socket是實現(xiàn)遠(yuǎn)程通信的一種方式,它基于TCP/IP協(xié)議。以下是一個簡單的Java Socket遠(yuǎn)程通信示例,包括客戶端和服務(wù)器端:
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();
}
}
在這個示例中,服務(wù)器端監(jiān)聽指定端口(12345),當(dāng)客戶端連接時,服務(wù)器接收客戶端發(fā)送的消息,并向客戶端發(fā)送回復(fù)??蛻舳诉B接到服務(wù)器后,發(fā)送一條消息給服務(wù)器,然后接收服務(wù)器的回復(fù)。
要運行這個示例,首先啟動服務(wù)器端代碼,然后啟動客戶端代碼。注意,如果客戶端和服務(wù)器端運行在不同的機器上,需要將服務(wù)器地址更改為服務(wù)器的IP地址。