Cocos Creator 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文件夹内导入类库

不用导入为插件…

  1. 引入类库
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);

}

最后更新时间:2018-03-02 13:16:08
坚持原创技术分享,您的支持将鼓励我继续创作!
原文网址:https://allknowboy.com/posts/e8f856f4/

包打听 包打听

  •  
  •  
  •  
  •  
  •  
  •  
  •  

Like Issue Page

No Comment Yet

 

Login with GitHub

 

Styling with Markdown is supported

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值