cocoscreator:websocket整合使用protobuf
-
var Message = Builder.build("game.service.data.MsgLoginData");
-
var loginMessage = new Message();
-
loginMessage.set("UserAccount","webTest");
-
loginMessage.set("UserPassWord","123456");
-
var msgBuf = loginMessage.<span style="color:#ff0000;">encode().toBuffer()</span>;
1.資料打包
在protobuf資料結構填寫完成後,即可呼叫encode().toBuffer()將物件轉換為ArrayBuffer物件,使用websockt傳送資料即可
-
var Message = Builder.build("game.service.data.MsgLoginResult");
-
var msg = Message.decode(messageBuff);
-
if(cc.sys.isNative){
-
webSocket.onDataReceived(event.data);
-
}else {
-
var fileReader = new FileReader();
-
fileReader.onload = function(progressEvent) {
-
var arrayBuffer = this.result; // arrayBuffer即為blob對應的arrayBuffer
-
webSocket.onDataReceived(arrayBuffer);
-
};
-
fileReader.readAsArrayBuffer(event.data);
-
}
2.資料接收,資料接收有一個需要注意,需要判斷是原生環境還是瀏覽器環境,如果是瀏覽器環境websocket收到的data將是BLOB型別,需要將BLOB型別轉換為ArrayBuffer,
如果是原生環境,直接使用即可
轉載。 https://blog.csdn.net/wzh200x/article/details/51859483