Egret officially provides a Websocket library that allows us to easily interact with the server over long connections.

Custom webSocket protocol format for header writing. To clarify, it’s not that we’re touching websocket itself, we’re agreeing on a server/client interaction format within the WebSocket transport.

To get this straight:

  1. Select the serialization method
  2. Agree on an interaction format
  3. Encapsulate a simple NetMgr (Network Management class)

Select serialization method:

At present, there are three mainstream serialization methods of XML JSON Protobuf. After consideration, I decide to choose JSON for the following reasons: 1. Better support for complex formats than Protobuf. 2. Saves more traffic than XML. 3. Json serialization is more convenient because of TypeScript selection. Protobuf has some problems in wechat applet. So I’m going to go with JSON.

Agree an interaction format:

CMD: command. Data: data. CmdType: command type

class Protocol<T> {

    public cmd: string;

    public data: T;

    public cmdType: CMDTYPE;


}
enum CMDTYPE {
    RECHARGE,
    NET,
    OTHER
}
Copy the code

Encapsulate a simple NetMgr:

NetMgr encapsulates the NetMgr class by shielding the game logic and basic network operations, and passing network data to the interface through Egret’s event mechanism. To send data to the server, also operate NetMgr only. No direct contact with Websocket.

Simple event class encapsulation

class NetEvent extends egret.Event { public cmd: string = "NetEvent"; public data: any; public constructor(type: string, bubbles: boolean = false, cancelable: boolean = false) { super(type, bubbles, cancelable); }}Copy the code

NetMgr class

// TypeScript file /** * class NetMgr extends Egret. DisplayObject {private socket: egret.WebSocket = new egret.WebSocket(); static net: NetMgr; constructor() { super(); } public static GetInstance(): NetMgr { if (this.net == null) this.net = new NetMgr(); return this.net; } public StartSocket(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) } public GetStatus(): boolean { return this.socket.connected; } onReceiveMessage(): void {console.log(" Received message :"); var msg = this.socket.readUTF(); console.log(msg); let protocol: Protocol<any> = JSON.parse(msg); // if (protocol.cmd) { try { let event = new NetEvent(NetEvent.Net); event.cmd = protocol.cmd; event.data = protocol; This.dispatchevent (event)} catch (error) {console.error(" network event :" + protocol. CMD + "- handle error ")}} Close(): Void {console.log(" Connection closed ")} onSocketOpen(): void {console.log(" network connection successful "); } IOError(): void {console.log(" network connection is down ")} public Emit<T>(CMD: string, data: T): void { if (this.socket.connected) { let protocol = new Protocol<T>(); protocol.cmd = cmd; protocol.data = data; this.socket.writeUTF(JSON.stringify(protocol)); }}}Copy the code

Simple network operations and serialization, and then there are disconnection reconnection and so on, on the later optimization. (I usually make things implement first, then optimize)

How do you use it?

1. Receive data from the server

Netmgr.getinstance ().addeventListener (NetEvent.Net, (e: NetEvent) => {console.log(" Event received from network "+ e.data)}, this)Copy the code

2. Send data to the server

    let demo = new TestDemo();
                demo.Data = "wocao";
                NetMgr.GetInstance().Emit<TestDemo>("serverAction", demo);
Copy the code

Ok, so that’s it

Need to pay attention to the big guy, can consider entering our QQ group: 753357671