Egret officially provides a websocket library that allows us to easily interact with long server connections.
When the title is written, customize the WebSocket protocol format. To explain, not to say that we go to the websocket itself, we are in the websocket of the transmission content of a set of server and customer interaction format.
Take a look at the idea:
- Choose how to serialize
- Convention an interactive format
- Encapsulates a simple netmgr (Network management Class)
Select the serialization method:
Currently the mainstream of the serialization method generally on three kinds of XML JSON protobuf, after consideration, I decided to choose JSON, because: 1. Support for complex formats is better than PROTOBUF. 2. Save more traffic than XML. 3. Because the choice of time typescript, so JSON serialization more convenient, I see Egret Forum response Protobuf in the small program has a problem. So combine it and choose JSON.
Conventions an interactive format:
Format is three fields: 1.cmd: Command 2. Data 3. Cmdtype: Command type
class Protocol<t> { publicstring; Public data:t; Public Cmdtype:cmdtype;} enum Cmdtype { recharge, NET, other }
Encapsulates a simple netmgr:
Encapsulation Netmgr This class is mainly to the game logic and the basis of the network operation part of the shield, through the Egret event mechanism to pass the network data to the interface layer. Send data to the server, and only operate netmgr. No direct contact with WebSocket.
Simple Event-Class encapsulation
class Netevent extends Egret. Event { publicstring'netevent'; Public Data:any; Public string false false { super (type, bubbles, cancelable); }}
Netmgr class
//TypeScript File/** * Network management class*/classNetmgr extends Egret. Displayobject {PrivateSocket:egret. WebSocket =NewEgret. WebSocket (); StaticNet:netmgr; Constructor () {super (); } Public Staticgetinstance (): netmgr {if( This. NET = =NULL) This. NET =Newnetmgr (); return This. NET; } PublicStartsocket (ServerIP:string, Port:number):void { if( This. socket.connected)return; This. Socket.addeventlistener (Egret. Progressevent.socket_data, This. Onreceivemessage, This); This. Socket.addeventlistener (Egret. Event.connect, This. Onsocketopen, This); This. Socket.addeventlistener (Egret. Ioerrorevent.io_error, This. IOError, This); This. Socket.addeventlistener (Egret. Event.close, This. Close, This); This. Socket.connect (ServerIP, Port)} PublicGetStatus (): boolean {return This. socket.connected; } onreceivemessage ():void{Console.log ("Receiving message:"); varmsg = This. Socket.readutf (); Console.log (msg); Let Protocol:protocol<any> =json.parse (msg); //if (protocol.cmd) { Try{ LetEvent=Newnetevent (netevent.net); Event. cmd =Protocol.cmd; Event. data =Protocol; This. dispatchevent (Event) } Catch(Error) {Console.error ("Network events:"+ Protocol.cmd +"-Handling Errors")}}} Close ():void{Console.log ("Connection Close")} onsocketopen ():void{Console.log ("network connectivity is successful"); } IOError ():void{Console.log ("Network Connection Disconnected") } PublicEmit<t> (cmd:string, data:t):void { if( This. socket.connected) {Let protocol=NewProtocol<t>(); Protocol.cmd=cmd; Protocol.data=data; This. Socket.writeutf (json.stringify (protocol)); } }}
Simple network operation and serialization just like this, there are broken network re-connected, and so on, and then optimize. (I usually do things first to achieve, then optimize)
How to use it??
1. Receiving the server's data
Netmgr.getinstance (). AddEventListener (Netevent.net, (e:netevent) = { console.log (" Receive the event " + e.data)" on the network)
2. Sending data to the server
New Testdemo (); " Wocao " ; Netmgr.getinstance (). Emit<TestDemo> ("serveraction", demo);
All right, this piece of content is here.
Need to continue to pay attention to the big guy, you can consider into our QQ group: 753357671
Online game development-Client 2 (custom WebSocket protocol format)