java Socket服务端客户端以tcp协议发送接收报文16进制
时间: 2023-08-19 17:04:52 浏览: 288
以下是Java中基于TCP协议的Socket通讯,发送和接收16进制报文的代码示例:
服务端代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
// 创建服务端Socket并绑定端口号
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务端已启动,等待客户端连接...");
// 等待客户端连接
Socket socket = serverSocket.accept();
System.out.println("客户端已连接");
// 获取输入流
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int len;
// 循环读取数据
while ((len = inputStream.read(buffer)) != -1) {
// 将字节数组转换为16进制字符串
String hexString = bytesToHexString(buffer, len);
System.out.println("收到客户端消息:" + hexString);
}
// 关闭流和Socket
inputStream.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 将字节数组转换为16进制字符串
private static String bytesToHexString(byte[] bytes, int len) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
String hex = Integer.toHexString(bytes[i] & 0xff);
if (hex.length() == 1) {
sb.append("0");
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
}
```
客户端代码:
```java
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try {
// 创建客户端Socket并连接服务端
Socket socket = new Socket("127.0.0.1", 8888);
// 获取输出流
OutputStream outputStream = socket.getOutputStream();
// 发送16进制报文
String hexString = "AABBCCDD";
byte[] bytes = hexStringToBytes(hexString);
outputStream.write(bytes);
// 关闭流和Socket
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 将16进制字符串转换为字节数组
private static byte[] hexStringToBytes(String hexString) {
int len = hexString.length() / 2;
byte[] bytes = new byte[len];
for (int i = 0; i < len; i++) {
bytes[i] = (byte) Integer.parseInt(hexString.substring(i * 2, i * 2 + 2), 16);
}
return bytes;
}
}
```
以上代码示例中,服务端通过创建ServerSocket监听端口8888,等待客户端连接。客户端通过创建Socket连接服务端,并获取输出流发送16进制报文。服务端通过获取输入流读取数据,并将字节数组转换为16进制字符串。客户端和服务端均提供了将16进制字符串转换为字节数组和将字节数组转换为16进制字符串的方法,方便进行数据转换。
阅读全文