1. 程式人生 > >Cocos Creator WebSocket

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類庫

  • 主要用於註冊和分發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);

}

No Comment Yet

Login with GitHub