egret.websocket的使用
egret.WebSocket 類(lèi)啟用代碼以建立傳輸控制協(xié)議 (TCP) 套接字連接,用于發(fā)送和接收字符串或二進(jìn)制數(shù)據(jù)出刷。套接字以異步方式傳輸和接收數(shù)據(jù)璧疗。
//下面上socket實(shí)例
public Connect(ip:string,port:number){
//創(chuàng)建 WebSocket 對(duì)象
this.socket = new egret.WebSocket();
//設(shè)置數(shù)據(jù)格式為二進(jìn)制,默認(rèn)為字符串
this.socket.type = egret.WebSocket.TYPE_BINARY;
//添加收到數(shù)據(jù)偵聽(tīng)馁龟,收到數(shù)據(jù)會(huì)調(diào)用此方法
this.socket.addEventListener(egret.ProgressEvent.SOCKET_DATA, (e:egret.Event)=>{
this.socket.readBytes(this._recvCache, this._recvCache.length);
this.handler()
}, this);
//添加鏈接打開(kāi)偵聽(tīng)崩侠,連接成功會(huì)調(diào)用此方法
this.socket.addEventListener(egret.Event.CONNECT,(e:egret.Event)=>{
this.trace("WebSocketOpen");
}, this);
//添加鏈接關(guān)閉偵聽(tīng),手動(dòng)關(guān)閉或者服務(wù)器關(guān)閉連接會(huì)調(diào)用此方法
this.socket.addEventListener(egret.Event.CLOSE,(e:egret.Event)=>{
this.trace("WebSocketClose");
}, this);
//添加異常偵聽(tīng)屁柏,出現(xiàn)異常會(huì)調(diào)用此方法
this.socket.addEventListener(egret.IOErrorEvent.IO_ERROR, (e:egret.Event)=>{
this.trace("WebSocketError");
}, this);
this.socket.connect(ip, port);
}
public SendString(id:number,str:string){
let body = new egret.ByteArray();
body.writeUTFBytes(str);
body.position = 0;
let msg = new egret.ByteArray();
msg.writeShort(body.length+2);
msg.writeShort(id);
msg.writeBytes(body)
var len: number = body.length;
if(len > 0){
this.socket.writeBytes(msg);
this.socket.flush();
}
}
/** 接受到數(shù)據(jù)時(shí)調(diào)用此函數(shù) */
private handler():void{
if(this._recvCache.length == 0){
return;
}
while(this._recvCache.bytesAvailable >= 2){
if(this._messageLength == -1){
this._messageLength = this._recvCache.readUnsignedShort()-2;
}
if(this._messageId == -1){
this._messageId = this._recvCache.readUnsignedShort();
}
if(this._messageLength <= this._recvCache.bytesAvailable){
if(this._messageLength==0){
this.parseData(this._messageId , null);
}else{
let _data = new egret.ByteArray();
this._recvCache.readBytes(_data, 0, this._messageLength);
this.parseData(this._messageId , _data);
}
this._messageId = -1;
this._messageLength = -1;
}
else{
break;
}
}
if(this._recvCache.position == this._recvCache.length){
this._recvCache.clear();
}
}
private _msgCount:number=0;
private parseData(ID:number,messageByte:egret.ByteArray) : void{
if(ID<=0){
console.log("webSocket 錯(cuò)誤啦膜!parseData:messageID < =0");
return;
}
//根據(jù)消息獲取數(shù)據(jù)具體類(lèi)型
if(framework.net.Protobuf.Ins.IdByClassName(ID.toString())){
var clazz:any = framework.net.Protobuf.Ins.GetIdByClass(ID.toString(),messageByte);
if(data.Config.IsDebug)
console.log("socket handler message type:",ID,"clsss:",clazz.toString()," index:",this._msgCount++);
core.Controller.Ins.SendName(Socket.SocketMessageEvent,[ID.toString(),clazz]);
//core.Controller.Ins.SendName(ID.toString(),messageByte);
}else
if(Game.Ins.Config.IsDebug)console.log("錯(cuò)誤,無(wú)法解析消息,消息ID:",ID);
return;
}
private trace(msg:any):void {
console.log(msg);
}
該例發(fā)送和接收 格式是
allmessage.length + id + content淌喻,
即2個(gè)字節(jié)的消息體總長(zhǎng)度 + 2個(gè)字節(jié)的消息ID + 消息內(nèi)容
所以算長(zhǎng)度時(shí)發(fā)送時(shí) 是內(nèi)容的length + 2僧家,接收消息算長(zhǎng)度時(shí)都需要 - 2來(lái)處理,每接收到消息都會(huì)判斷 while(this._recvCache.bytesAvailable >= 2) 則代表消息內(nèi)容存在裸删,if(this._messageLength <= this._recvCache.bytesAvailable) 則是為了確保消息的準(zhǔn)確性
2019.2.13
本文中數(shù)據(jù)類(lèi)型采用protobuf存儲(chǔ)
以下根據(jù)消息ID八拱,以及流數(shù)據(jù),創(chuàng)建具體實(shí)類(lèi)
let className:string =this.IdByClassName(ID);
let cls = this.protobuff.build(className);
if(message == null){
return new cls();
}
if(!className){
if(Game.Ins.Config.IsDebug)console.log("錯(cuò)誤,無(wú)法解析消息,消息ID:",ID,'將返回結(jié)果滯空來(lái)跳過(guò)該類(lèi)');
return null;
}
return cls.decode(message.buffer);