一只腊鸭做游戏Laya游戏开发实战

Laya WebSocket

2019-11-27  本文已影响0人  s0ok

关于webSocket我们不做其他赘述,有兴趣可以看下HTML5 WebSocket

Laya.Scoket

Name Summary
connected 表示此 Socket 对象目前是否已连接。
disableInput 不再缓存服务端发来的数据。
endian 主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。
input 缓存的服务端发来的数据。
output 表示需要发送至服务端的缓冲区中的数据。
protocols 子协议名称。子协议名称字符串,或由多个子协议名称字符串构成的数组。
Name Summary
Socket 创建新的 Socket 对象。默认字节序为 Socket.BIG_ENDIAN 。
cleanSocket 清理socket。
close 关闭连接。
connect 连接到指定的主机和端口。
connectByUrl 连接到指定的服务端 WebSocket URL。
flush 发送缓冲区中的数据到服务器。
send 发送数据到服务器。

Laya.Socket使用

private webSocket: Laya.Socket;
    private openBtn: Laya.Button;
    private sendBtn: Laya.Button;
    private closeBtn: Laya.Button;
    initWebSocket() {
        this.openBtn = new Laya.Button(null, '连接服务器');
        this.openBtn.width = 150,
            this.openBtn.height = 50
        this.openBtn.labelSize = 30;
        this.openBtn.labelColors = '#FFFFFF';
        this.openBtn.x = 200;
        this.openBtn.y = 150;
        Laya.stage.addChild(this.openBtn);

        this.sendBtn = new Laya.Button(null, '发送消息');
        this.sendBtn.width = 150,
            this.sendBtn.height = 50
        this.sendBtn.labelSize = 30;
        this.sendBtn.labelColors = '#FFFFFF';
        this.sendBtn.x = 200;
        this.sendBtn.y = 350;
        Laya.stage.addChild(this.sendBtn);

        this.closeBtn = new Laya.Button(null, '断开服务器');
        this.closeBtn.width = 150,
            this.closeBtn.height = 50
        this.closeBtn.labelSize = 30;
        this.closeBtn.labelColors = '#FFFFFF';
        this.closeBtn.x = 200;
        this.closeBtn.y = 550;
        Laya.stage.addChild(this.closeBtn);

        //初始化Socket对象
        this.webSocket = new Laya.Socket();
        this.webSocket.on(Laya.Event.OPEN, this, this.openHandler);//连接正常打开抛出的事件
        this.webSocket.on(Laya.Event.MESSAGE, this, this.receiveMsgHandler);//接收到消息抛出的事件
        this.webSocket.on(Laya.Event.CLOSE, this, this.closeHandler);//socket关闭抛出的事件
        this.webSocket.on(Laya.Event.ERROR, this, this.errorHandler);//连接出错抛出的事件

        //点击按钮链接服务器
        this.openBtn.on(Laya.Event.CLICK, this, () => {
            this.webSocket.connectByUrl("wss://ws2s.feling.net/");
        })
        //点击按钮发送消息
        this.sendBtn.on(Laya.Event.CLICK, this, () => {
            this.webSocket.send('{"command":"connect","host":"ip.feling.net","port":80}');
        })
        //点击按钮断开链接
        this.closeBtn.on(Laya.Event.CLICK, this, () => {
            this.webSocket.close();
        })

    }

    openHandler(msg) {
        console.log("webSocket链接成功,可以发送消息.");
    }

    receiveMsgHandler(msg) {
        console.log("收到服务器消息: " + JSON.stringify(msg));
    }

    closeHandler(msg) {
        console.log("与服务器连接断开.");
    }

    errorHandler(msg) {
        console.log("与服务器通信错误.");
    }

大致通信流程:
客户端发起链接—>链接成功响应OPEN事件
客户端发送消息—>服务端接受到消息处理完后进行回调—>客户端响应MESSAGE事件
客户端断开链接—>断开链接响应Close事件

上一篇 下一篇

猜你喜欢

热点阅读