网络游戏开发-客户端2(自定义websocket协议格式)

简介: 网络游戏开发-客户端2(自定义websocket协议格式)

Egret官方提供了一个Websocket的库,可以让我们方便的和服务器长连接交互。

标题写的时候自定义websocket的协议格式。解释一下,不是说我们去动websocket本身的东西,我们是在websocket的传输内容里面约定一套服务器和客户的交互格式。

捋一下思路:

  1. 选择序列化的方式
  2. 约定一个交互格式
  3. 封装一个简单的NetMgr(网络管理类)

选择序列化方式:

目前主流的序列化方式一般就三种 xml json protobuf,经过考虑,我决定选择json,原因是:1.对复杂的格式支持比protobuf好。2.比xml更节约流量。3.因为选择的时候TypeScript,所以json序列化更方便,我看egret论坛有反应protobuf在微信小程序中有问题。所以综合一下,就选择json吧。

约定一个交互格式:

格式就三个字段:1.cmd :命令 2. data 数据 3. CmdType:命令类型

class Protocol<T> {
    public cmd: string;
    public data: T;
    public cmdType: CMDTYPE;
}
enum CMDTYPE {
    RECHARGE,
    NET,
    OTHER
}

封装一个简单的NetMgr:

封装NetMgr这个类主要是想把游戏逻辑和基础的网络操作部分屏蔽,通过Egret的事件机制来传递网络数据到界面层。发送数据给服务器,也只操作NetMgr。不会直接接触websocket。

简单的事件类封装

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);
    }
}

NetMgr类

// 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("接收到消息:");
        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("网络事件:" + protocol.cmd + "-处理错误")
        }
    }
    Close(): void {
        console.log("连接关闭")
    }
    onSocketOpen(): void {
        console.log("网络连接成功");
    }
    IOError(): void {
        console.log("网络连接断开")
    }
    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));
        }
    }
}

简单的网络操作和序列化就这样了,后面还有断网重连之类的,就后面再优化。(我一般做东西都是先实现,再优化)

如何使用呢??

1.接收服务器的数据

NetMgr.GetInstance().addEventListener(NetEvent.Net, (e: NetEvent) => {
                console.log("接受到网络派发的事件" + e.data)
            }, this)

2.给服务器发送数据

 

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

好了,这块内容就到这里了

目录
相关文章
|
4天前
|
算法 网络协议
生成树协议:网络稳定的守护者
【4月更文挑战第22天】
10 0
|
6天前
|
缓存 网络协议 网络架构
【计算机网络】第三章 数据链路层(MAC地址 IP地址 ARP协议)
【计算机网络】第三章 数据链路层(MAC地址 IP地址 ARP协议)
12 1
|
6天前
|
网络协议 算法 网络虚拟化
【计算机网络】第三章 数据链路层(点对点协议 媒体介入控制)
【计算机网络】第三章 数据链路层(点对点协议 媒体介入控制)
14 0
|
2天前
|
安全 网络协议 算法
【计算机网络】http协议的原理与应用,https是如何保证安全传输的
【计算机网络】http协议的原理与应用,https是如何保证安全传输的
|
3天前
|
负载均衡 网络虚拟化
【专栏】全网对 STP 生成树协议最全面最优质的总结,网络工程师收藏!
【4月更文挑战第28天】本文详细介绍了生成树协议(STP),用于消除网络环路并确保单向通信路径。STP基于IEEE 802.1D,涉及根桥选举、端口角色分配及构建无环路径。高级特性包括快速STP(RSTP)的快速收敛、多实例STP(MSTP)的负载均衡和容错,以及各种保护机制。文章还讨论了实际案例和故障排除,为网络工程师提供STP的全面理解与应用指南。
|
4天前
|
网络协议 Linux iOS开发
|
4天前
|
监控 安全 网络虚拟化
|
12天前
|
域名解析 存储 缓存
《计算机网络简易速速上手小册》第2章:计算机网络协议和标准(2024 最新版)
《计算机网络简易速速上手小册》第2章:计算机网络协议和标准(2024 最新版)
8 3
|
14天前
|
网络协议 Java API
深度剖析:Java网络编程中的TCP/IP与HTTP协议实践
【4月更文挑战第17天】Java网络编程重在TCP/IP和HTTP协议的应用。TCP提供可靠数据传输,通过Socket和ServerSocket实现;HTTP用于Web服务,常借助HttpURLConnection或Apache HttpClient。两者结合,构成网络服务基础。Java有多种高级API和框架(如Netty、Spring Boot)简化开发,助力高效、高并发的网络通信。
|
15天前
|
存储 网络协议 安全
15.网络协议-Radius协议
15.网络协议-Radius协议