Open wangguixi opened 6 years ago
@wangguixi I'd approach this issue by treating the protobuf protocol data that you want to send/receive as any other binary data that you can send/receive with socket.io protocol. You may want to take a look at binary event demo from netty-socketio for binary data support example.
@wangguixi
gps_data.proto file content : syntax = "proto3"; message gps_data { int64 id = 1; string terminalId = 2; string dataTime = 3; double lon = 4; double lat = 5; float speed = 6; int32 altitude = 7; int32 locType = 8; int32 gpsStatus = 9; float direction = 10; int32 satellite = 11; }
springboot code: //使用protobuf 测试传输的数据 @OnEvent(value = "protobufTest") public void onProtobufTest(SocketIOClient client, AckRequest ackRequest, byte[] data) throws InvalidProtocolBufferException, UnsupportedEncodingException { if (ackRequest.isAckRequested()) { ackRequest.sendAckData(data); } GpsData.gps_data gps_data = GpsData.gps_data.parseFrom(data); System.out.println("after :" + gps_data.getTerminalId() + gps_data.getDataTime()); }
//前端代码: Front end code:
protobuf.load("/protobuf/gps_data.proto", function (err, root) {
if (err) throw err;
gps_data = root.lookupType("gps_data");
let message = gps_data.create({dataTime: "2018-07-03", terminalId: "222 你好"});
console.log(message = ${JSON.stringify(message)}
);
let buffer = gps_data.encode(message).finish();
console.log(`buffer = ${Array.prototype.toString.call(buffer)}`);
//参考文章: https://www.cnblogs.com/gradolabs/p/4762134.html
var bufArr = new ArrayBuffer(buffer.length);
var bufView = new Uint8Array(bufArr);
bufView.set(buffer)
console.log(bufArr)
socket.emit("protobufTest", bufArr, function (data) {
console.log("后台 传回来的 byte 数据 :==============》")
var d = new Uint8Array(data.byteLength);
var dataView = new DataView(data);
for (var i = 0; i < data.byteLength; i++) {
d[i] = dataView.getInt8(i);
}
console.log(d)
let decoded = gps_data.decode(d);
console.log(`decoded = ${JSON.stringify(decoded)}`);
})
});
@githuanl great!!!! Thanks!!!!
Netty-socketio uses JSON as the converter by default, and an error will be reported when the front-end transfers byte.
HI: In the web page, If don't use the json protocol and use the protobuf protocol, how do I change the server? Thank you very much!!!!!!