【发布时间】:2017-12-06 14:43:04
【问题描述】:
我正在开发一个 Angular5+ 前端,它使用带有 WebSocket 的 google-protobuf JS 与后端进行通信。
我的 .proto 文件中目前有 2 个对象:
- 一个请求对象。
- 一个通知对象。
然后我创建了一个处理程序服务,它将通过 WebSocket 发送消息,但后来我遇到了一个大问题:我找不到有效地解析/反序列化我的对象的方法:
this._socketService.getSocket().onmessage = ((message: Message) => {
const uiArray = new Uint8Array(message.data);
this.parseMessage(uiArray);
});
parseMessage(uiArray: Uint8Array) {
let response = null;
// DOES NOT WORK
// response = reqRep.Response.deserializeBinary(uiArray) || notif.BackendStatusNotification.deserializeBinary(uiArray);
// <==== This is where I need to find a good way to deserialize efficiently my objects
// TEMPORARY
if (uiArray.byteLength === 56) {
response = reqRep.Response.deserializeBinary(uiArray)
} else {
response = notif.BackendStatusNotification.deserializeBinary(uiArray);
}
// Notify different Observables which object has changed based on their type
switch (response && response.hasSupplement() && response.getSupplement().array[0]) {
case 'type.googleapis.com/req.BackendStatusResponse':
this._responseSubject.next(response);
break;
case 'type.googleapis.com/notif.BackendStatusNotification':
this._notificationSubject.next(response);
break;
default:
console.log('DOESN\'T WORK');
}
}
我尝试使用代码中所示的|| 始终能够反序列化我的响应,但它不起作用:如果第一个失败,我会收到运行时错误。
我有一些见解,但也许有人可以帮助我:
- 要么我必须做
trycatch来管理每个案例(这显然是最糟糕的解决方案)。 - 我在尝试反序列化的方式上做错了,这是一个愚蠢的错误。我虽然也许
我可以使用来自
google-protobuf的通用Message.deserialize(),但这是行不通的,因为每个对象都应该实现自己的反序列化方法。 - 或者最后一个,我应该创建一个
.proto文件,在其中设置一个基础对象,该对象将为我的应用程序嵌套所有不同的对象。这样我可以反序列化一种类型的消息,该消息将能够用它反序列化嵌套对象。 (对我来说,这是最好的解决方案,但后端成本很高)
【问题讨论】:
标签: javascript angular websocket protocol-buffers