Linuxc++socket 接收protobuf并解码的demo,每一条消息由消息头、消息体组成。消息采用单字节对齐方式。本接口规范中的所有整数类 型字段都采用低字节序(LITTLE-ENDIAN)编码方式。如用 java 开发客户端接收程序, 需要转整数字段换字节序。
时间: 2024-03-05 15:47:59 浏览: 106
这里是一个 Java 的示例代码,用于接收 protobuf 消息并解码,假设消息头的长度为 4 字节、包含消息体长度和消息类型两个字段,消息体为 protobuf 格式:
```java
import java.io.InputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import com.google.protobuf.Message;
public class MessageReceiver {
// 消息头长度
private static final int HEADER_LENGTH = 4;
// 接收数据
private static int receiveData(InputStream in, byte[] buffer, int length) throws Exception {
int recvLen = 0;
while (recvLen < length) {
int ret = in.read(buffer, recvLen, length - recvLen);
if (ret < 0) {
throw new Exception("Socket receive error");
}
recvLen += ret;
}
return recvLen;
}
// 接收并解析消息
public static boolean receiveMessage(Socket socket, Message.Builder builder) {
try {
InputStream in = socket.getInputStream();
// 接收消息头
byte[] header = new byte[HEADER_LENGTH];
if (receiveData(in, header, HEADER_LENGTH) != HEADER_LENGTH) {
return false;
}
// 解析消息头
int bodyLength = ByteBuffer.wrap(header).order(ByteOrder.LITTLE_ENDIAN).getInt();
int messageType = ByteBuffer.wrap(header, 4, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
// 接收消息体
byte[] body = new byte[bodyLength];
if (receiveData(in, body, bodyLength) != bodyLength) {
return false;
}
// 解码消息体
builder.clear();
builder.mergeFrom(body);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
```
使用示例:
```java
Socket socket = new Socket("127.0.0.1", 8080);
// 接收并解析消息
MyMessage.Builder builder = MyMessage.newBuilder();
if (MessageReceiver.receiveMessage(socket, builder)) {
MyMessage msg = builder.build();
// 处理消息
...
}
socket.close();
```
阅读全文