Java Socket是实现远程通信的一种方式,它基于TCP/IP协议。以下是一个简单的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),当客户端连接时,服务器接收客户端发送的消息,并向客户端发送回复。客户端连接到服务器后,发送一条消息给服务器,然后接收服务器的回复。
要运行这个示例,首先启动服务器端代码,然后启动客户端代码。注意,如果客户端和服务器端运行在不同的机器上,需要将服务器地址更改为服务器的IP地址。