TCP通信练习--多发多收 客户端:多次发送数据 服务器:接收多次接收数据,并打印
时间: 2024-11-30 10:15:49 浏览: 16
在TCP通信中,"多发多收"通常指的是客户端能够多次发送数据,而服务器则能接收并处理这些连续的数据包。以下是一个简单的Java示例,展示了如何在客户端和服务器端实现这样的功能:
**客户端(Client)**:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
String message = "Hello, Server! This is a multi-message TCP client.";
int port = 8000; // 假设服务器监听的端口
Socket socket = new Socket("localhost", port);
PrintStream out = new PrintStream(socket.getOutputStream());
for (int i = 0; i < 5; i++) { // 发送5次消息
out.println(message + " - Message " + (i+1));
Thread.sleep(1000); // 暂停一秒增加模拟延迟
}
socket.close();
}
}
```
**服务器(Server)**:
```java
import java.io.*;
import java.net.*;
public class Server extends Thread {
private ServerSocket serverSocket;
private Socket clientSocket;
public Server(int port) {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
}
@Override
public void run() {
while (true) {
try {
clientSocket = serverSocket.accept(); // 等待客户端连接
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line;
while ((line = in.readLine()) != null) { // 接收并打印每条消息
System.out.println("Received from client: " + line);
}
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
break;
}
}
serverSocket.close();
}
public static void main(String[] args) {
int port = 8000;
Server server = new Server(port);
server.start();
}
}
```
在这个例子中,客户端循环发送5次消息,每次之间有短暂的暂停(这里只是为了演示),服务器则不断地接受和打印接收到的消息,直到客户端关闭连接。
阅读全文