java实现TCP客户端,服务端相互通信
时间: 2024-10-11 20:18:02 浏览: 33
在Java中实现TCP客户端和服务端通信,通常需要使用`java.net.Socket`类(用于创建连接)和`ServerSocket`类(用于监听连接)。以下是简单的步骤:
**服务端(Server):**
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8080); // 监听8080端口
System.out.println("Server is running on port 8080");
while (true) {
Socket clientSocket = server.accept(); // 等待客户端连接
try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String requestLine;
while ((requestLine = in.readLine()) != null) { // 读取客户端数据
System.out.println("Received: " + requestLine);
out.println("Echoing: " + requestLine); // 发回给客户端
}
} finally {
clientSocket.close();
}
}
}
}
```
**客户端(Client):**
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
String hostname = "localhost"; // 如果是远程服务器,则替换为你服务器地址
int port = 8080;
Socket socket = new Socket(hostname, port);
System.out.println("Connected to server at " + hostname + ":" + port);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String userInput;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput); // 发送数据到服务器
System.out.println("Sent: " + userInput);
String response = in.readLine(); // 接收服务器响应
System.out.println("Received: " + response);
}
socket.close();
}
}
```
以上示例是一个基础的TCP文本通信,客户端发送一行就接收一行回复。运行服务端程序,然后在客户端启动交互。
阅读全文