cocos creator中javaScript使用WebSoc
2019-02-16 本文已影响2人
洒一地阳光_217d
本文中使用WebSocket与服务器长连接,通信采用的是protobuf:如何在javascript环境下使用google protobuf
Packet.proto
syntax = "proto2";
message Packet {
required int32 type = 1;
}
与服务器建立链接
let self = this;
// connectionProtocol(字符串协议参数 可选) 可为字符串或包含字符串的数组
let connectionProtocol = "";
//原生平台上使用 wss的websocket需要自己添加一个证书(浏览器或者微信小程序不需要填写此参数)
let pemUrl = cc.url.raw("resources/cert.pem")
let ws = new WebSocket(url, connectionProtocol, pemUrl);
ws.onopen = function (event) {
console.log("ws is open ");
};
ws.onmessage = function (event) {
self.onMessage(event.data);
};
ws.onerror = function (event) {
console.log("ws has an error ");
};
ws.onclose = function (event) {
console.log("ws is closed ");
};
向服务器发送消息
// 向服务器发送消息
let packet_pb = require('Packet_pb');
let packet = new packet_pb.Packet();
packet.setType(1);
let msg = packet.serializeBinary();
// 在某些平台, 如原生平台或者微信小程序, 发送的是 arrayBuffer
// 若在浏览器平台则直接发送msg
ws.send(msg.buffer);
接收服务器发来的消息
onMessage: function (msg) {
if (msg.constructor != null && msg.constructor.name == "Blob") {
//浏览器会得到一个blob对象,必须转化,否则不能解析
//将Blob 对象转换成 ArrayBuffer
let reader;
if (typeof (FileReader) == "undefined") {
reader = new FileReaderSync();
} else {
reader = new FileReader();
}
if (reader != null) {
let self = this;
reader.onload = function (e) {
self.processMessage(reader.result);
}
reader.readAsArrayBuffer(msg);
}
} else {
//原生平台和微信小游戏上接收到的直接是: ArrayBuffer
this.processMessage(msg, serverType);
}
},
processMessage: function (msg) {
let packet_pb = require('Packet_pb');
let u8Msg = new Uint8Array(msg);
let packet = packet_pb.Packet.deserializeBinary(u8Msg);
this.enqueuePacketReceived(packet, serverType);
},