CocosCreator中加入webSocket的使用

前言

使用WebSocket作为网络连接的方式,简单的使用文本传输,使用onfire做事件的分发,可以替换NetControl里面的websocket实现为socket和其他网络方案,只要修复onfire的激发,基本不用该游戏代码。

新建一个配置类

  • NetConfig.js
  • 用于配置网络的相关内容
  • 当前只有host port
  • 还可以配置其他的内容
/**
 * 当前的网络配置
 */
module.exports={
    host:"ws://localhost",
    port:9000

};

新建一个网络控制类

//定义全局的变量
window.onfire=require("onfire");           //处理事件的类库
var netConfig=require('NetConfig');
var NetControl={
    _sock:{},  //当前的webSocket的对象
    connect: function () {
        if(this._sock.readyState!==1){
            //当前接口没有打开
            //重新连接
            this._sock = new WebSocket(netConfig.host+":"netConfig.port); 
            this._sock.onopen = this._onOpen.bind(this);
            this._sock.onclose = this._onClose.bind(this);
            this._sock.onmessage = this._onMessage.bind(this);
        }
        return this;
    },

    _onOpen:function(){
        onfire.fire("onopen");
    },
    _onClose:function(err){
        onfire.fire("onclose",err);
    },
    _onMessage:function(obj){

        onfire.fire("onmessage",obj);
    },

    send:function(msg){
        this._sock.send(msg);
    },

};

module.exports=NetControl;

引入一个onfire类库

项目地址:
https://github.com/hustcc/onfire.js

  • 主要用于注册和分发webSocket的事件
  • 自己用listener写也是可以的
  • 不过 有类库干嘛不用呢

下面是onfire的例子

import onfire from 'onfire.js';

function test_callback(data1, data2) {
    console.log('this is a event 1');
}

// bind event and callback
var eventObj = onfire.on('test_event', test_callback);
var eventObj2 = onfire.on('test_event', function(data1, data2) {
    console.log('this is a event 2');
});

// fire event
onfire.fire('test_event', 'test_data1', 'test_data2');

// cancel bind event
onfire.un(eventObj); // only cancel the eventObj.
onfire.un('test_event'); // cancel all events named `test_event`.
onfire.un(test_callback); // cancel all the `test_callback` functions.

使用方法

  1. 拖入onfire.js到assert文件夹内导入类库
    不用导入为插件…

  2. 引入类库

var netControl=require('NetControl');
  1. 连接网络加入监听(可以多次注册同一方法)
netControl.connect();
this.msssageFire=onfire.on("onmessage",this.onMessage.bind(this));
  1. 本地监听方法
onMessage:function(obj){
    console.log("It's HelloWorld onMessage----->"+obj);
}
  1. 发送数据
var jsonTmp = "{ \"Mobile\": \"" + 121212 + "\", \"Password\": \"" + 121313454545 + "\" }"; 
netControl.send("1010" + jsonTmp);
console.log("sendToWS");
  1. 销毁事件的注册
onDestroy:function(){
    onfire.un(this.msssageFire);

}

原文地址:http://allknowboy.com/posts/e8f856f4/

9赞

非常谢谢~,很需要

onMessage:function(obj){
console.log(“It’s HelloWorld onMessage----->”+obj);
}

如果解析 接收到的 obj ?

cocos creator中可以使用GoEasy提供的websocket推送服务,无需搭建websocket服务器,使用typescript方式引入即可,支持wss、心跳、断线重连等机制,我们公司的小游戏项目就是用GoEasy做的,稳定很不错的。https://www.goeasy.io/