java tcp接口_使用Java编写TCP协议发送和接收数据接口
时间: 2024-01-15 11:02:51 浏览: 88
要使用Java编写TCP协议发送和接收数据接口,可以使用Java自带的Socket和ServerSocket类。
首先,创建一个ServerSocket对象,指定监听的端口号:
```java
ServerSocket serverSocket = new ServerSocket(8888);
```
然后,创建一个Socket对象,指定连接的IP地址和端口号:
```java
Socket socket = new Socket("127.0.0.1", 8888);
```
接下来,可以使用socket对象的输入输出流来发送和接收数据:
```java
// 发送数据
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello".getBytes());
// 接收数据
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
String result = new String(buffer, 0, len);
System.out.println(result);
```
当有客户端连接到ServerSocket时,可以使用accept()方法获取到一个Socket对象,然后就可以进行数据的收发了:
```java
Socket socket = serverSocket.accept();
```
完整的代码示例:
```java
// 服务端
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
String result = new String(buffer, 0, len);
System.out.println(result);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("world".getBytes());
socket.close();
serverSocket.close();
```
```java
// 客户端
Socket socket = new Socket("127.0.0.1", 8888);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello".getBytes());
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
String result = new String(buffer, 0, len);
System.out.println(result);
socket.close();
```
阅读全文