Java实现tcp通讯
时间: 2023-09-05 08:11:00 浏览: 102
Java可以使用Socket类和ServerSocket类来实现TCP通讯。下面是一个简单的示例:
1. 服务端实现
```java
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888); // 创建ServerSocket
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = serverSocket.accept(); // 监听客户端连接请求,阻塞等待
System.out.println("客户端已连接,客户端地址:" + socket.getInetAddress() + ",客户端端口号:" + socket.getPort());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 获取输入流
String line;
while ((line = reader.readLine()) != null) { // 循环读取客户端发送的消息
System.out.println("客户端发送的消息:" + line);
}
reader.close();
socket.close();
serverSocket.close();
}
}
```
2. 客户端实现
```java
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888); // 创建Socket并连接到服务端
System.out.println("连接服务器成功,服务器地址:" + socket.getInetAddress() + ",服务器端口号:" + socket.getPort());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // 从控制台读取输入的消息
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true); // 获取输出流
String line;
while ((line = reader.readLine()) != null) { // 循环读取用户输入的消息并发送给服务端
writer.println(line);
}
writer.close();
reader.close();
socket.close();
}
}
```
以上就是一个简单的Java实现TCP通讯的示例代码。
阅读全文