java实现tcp 发送和接收
时间: 2024-10-15 20:15:16 浏览: 16
java的TCP协议发送和接收消息
在Java中,我们可以使用java.net包下的Socket和ServerSocket类来实现TCP通信的发送和接收。以下是一个简单的客户端-服务器端模型:
### 客户端示例 (发送数据):
```java
import java.io.*;
import java.net.Socket;
public class TcpClient {
public static void main(String[] args) {
try {
// 创建Socket实例
Socket socket = new Socket("localhost", 8080); // 地址和端口
System.out.println("Connected to server");
// 获取OutputStream来发送数据
OutputStream outputStream = socket.getOutputStream();
String message = "Hello from client";
byte[] bytes = message.getBytes(); // 转换为字节数组
// 发送数据
outputStream.write(bytes);
outputStream.flush();
// 关闭连接
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
### 服务器端示例 (接收数据):
```java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080); // 监听的端口
System.out.println("Server started, listening on port 8080");
while (true) {
Socket clientSocket = serverSocket.accept(); // 等待并接受连接
try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: " + inputLine);
// 可在此处处理接收到的数据
out.println("Message received and acknowledged");
}
} finally {
clientSocket.close();
}
}
}
}
```
阅读全文