在小游戏 以至于大部分用cocoscreator开发的 游戏中 都可能用到。protobuf,webSocket,http,一般面试的内容中几乎也会有 他们。我管他们叫“三贱客”。本文贴出。第二贱 webSocket的使用方法。
代码:
let gameSocket = new class { socket = null; address = null; ip = null; port = null; /**创建websocket */ createSocket() { if (!this.socket) { let address =ws://${this.ip}:${this.port}` || this.address;
this.socket = new WebSocket(address);
this.socket.binaryType = “arraybuffer”;
this.addEvent();
}
return this.socket;
}
getSocket(){
return this.socket;
}
/**添加webSocket事件 */
addEvent() {
if (!this.socket) {
return;
}
//监听连接
this.socket.onopen = (event) => {
// todo
}
//监听关闭
this.socket.onclose = (event) => {
// todo
};
//监听出错
this.socket.onerror = (event) => {
// todo
}
//监听接收到信息
this.socket.onmessage = (event) => {
// todo
}
};
/**发送数据*/
sendMessage = function(msg, msgType)
{
//对应protobuf类
let protobufClass = Messages.getMessageClass()
//与服务器同步大小端并写入消息号 通常是两个字节
Byte.setBigEndian()
Byte.writeInt16(msgType);
//打包数据
let buffer:Uint8Array = protobufClass.encode(msg).finish();
let buf = GByte.writeArrayBuffer(buffer);
GByte.reset()
this.socket.send(buf);
}
/*读取服务器返回的数据/
onReceiveMessage(event){
//与服务器同步大小端
Byte.setBigEndian();
let messageType = Byte.readInt16(event.data);
//获取数据转换类并 解析数据
let protobufClass = MessageMap.getMessageClass();
let bufferArr = Byte.readArrayBuffer()
Byte.reset();
//解析
let decodeMsg = protobufClass.decode(bufferArr);
let eventMsg = decodeMsg.toJSON();
this.despatchEvent(eventMsg);
}
//分发事件
despatchEvent(eventMsg){
//todo
}
}();
window[“gameSocket”] = gameSocket;
`
长按下面二维码 关注公众号 选择联系作者。添加作者微信号获取完整源码或相关知识解答。
