cocos creator基础-(二十六)Websocket与socket.io

1: 掌握websocket基本使用;
2: 掌握socket.io基本使用;
 
websocket

1: creator只支持websocket,h5的标准也只支持websocket;
2: websocket 底层是 tcp socket,基于tcp socket上建立了连接,收发数据的标准,保证了用户收到的数据和发到的数据是一致的,不用考虑粘包等问题,websocket协议已经解决了;
3: websocket的使用方式:
  1>new WebSocket(url); 服务器对应的url: “ws://127.0.0.1:6081/ws”,ip + port
  2> 支持的数据: 文本数据类型与二进制数据类型;
    sock.binaryType = "arraybuffer"/”Blob”; 支持arraybuffer和Blob类型,一般配置成arraybuffer,根据服务器而定;
  3>配置好websocket的回掉函数:
    onopen(event),onmessage(event),onclose(event),onerror(event),
  4>不用了关闭socket或收到服务器关闭遇到错误: close方法;
4: 基于node.js来测试下websocket,node.js见服务器课程;

客户端代码

// websocket.js 导出的自己封装的websocket模块
var websocket = {
    sock: null,// 连接的socket 对象 WebSocket,h5标准对象;

    // 网络连接成功了以后调用
    on_open: function(event) {
        // test
        this.send_data("HelloWorld");
        // end
    },// 客户端收到数据的时候
    on_message: function(event) {
        console.log("#####",event.data);
    },// 客户端收到socket 关闭的时间的时候调用;
    on_close: function (event) {
        this.close();
    },on_error: function (event) {
        this.close();
    },close: function() {
        if (this.sock != null) {
            this.sock.close(); // 关闭socket
            this.sock = null;
        }
    },// 连接函数,
    connect: function(url) {
        this.sock = new WebSocket(url); // h5标准的websocket对象
        this.sock.binaryType = "arraybuffer"; // 配置接受二进制的数据类型,与服务器保持一次,"Blob"

        // 为这个websocket对象制定对应的回掉函数;
        this.sock.onopen = this.on_open.bind(this);
        this.sock.onmessage = this.on_message.bind(this);
        this.sock.onclose = this.on_close.bind(this);
        this.sock.onerror = this.on_error.bind(this);
    },// 发送数据,sock.send;
    send_data: function(data) {
        this.sock.send(data);
    },};


module.exports = websocket;
// game_scene.js 使用webscoket和socket.io的案例
var websocket = require("websocket");
var net = require("net");

cc.Class({
    extends: cc.Component,properties: {
        // foo: {
        //    default: null,// The default value will be used only when the component attaching
        //                           to a node for the first time
        //    url: cc.Texture2D,// optional,default is typeof default
        //    serializable: true,default is true
        //    visible: true,default is true
        //    displayName: ‘Foo‘,// optional
        //    readonly: false,default is false
        // },
        // ...
    },// use this for initialization
    onLoad: function () {
        // net.connect("127.0.0.1:6081");
        websocket.connect("ws://127.0.0.1:6080/ws");
    },// called every frame,uncomment this function to activate update callback
    // update: function (dt) {

    // },
});

服务器代码

// echo_server.js websocket服务器代码
var ws = require("ws");
var server = new ws.Server({
    // host: ip,// 如果加了host,外部链接不上
    port: 6080,});

console.log("#######");
function on_server_client_comming(session) {
    session.on("close",function() {
    });

    // error事件
    session.on("error",function(err) {
    });
    // end 

    session.on("message",function(data) {
        console.log("######",data);

        session.send(data);
    });
}
server.on("connection",on_server_client_comming);


var socket_io = require(‘socket.io‘)
var sio = socket_io(6081);

sio.sockets.on(‘connection‘,function(socket){
    console.log("connect called");

    // 自定义事件
    socket.on("your_echo",function (data) {
        console.log("your_echo",data);

        socket.emit("your_echo",data);
    });
    // end 

    // 系统事件
    socket.on(‘disconnect‘,function(data){
        console.log("disconnect");        
    });


});

 

socket.io
1: socket.io是基于 TCP socket/Websocket封装的 上层的一个框架;
2: 使得人们能方便的使用类似事件的模式来处理网络数据包;
3: creator 搭建socket.io注意:
  1>jsb里面原生实现了SocketIO;
  2>h5 使用js的实现socket-io.js; // 下载标准的socket.io.js,然后修改过滤掉原生平台的(!CC_JSB && !cc.sys.isNative);
4: socket.io的使用: 注意客户端服务器版本一定要对上,使用课堂提供的版本匹配
  1> connect: var opts = {
    ‘reconnection‘:false,
    ‘force new connection‘: true,
    ‘transports‘:[‘websocket‘,‘polling‘]
   }
  this.sio = window.io.connect(this.ip,opts);
  2>系统事件: connect/disconnect,connect_failed,
  3> 自定义事件:
  4> 关闭 this.sio.disconnect();

客户端代码

// 导出的net模块 net.js
if(window.io == null){ // h5
    window.io = require("socket-io");
}


var net = {
    sio: null,connect:function(url) {
        var self = this;
        
        var opts = {
            ‘reconnection‘:true,‘force new connection‘: true,‘transports‘:[‘websocket‘,‘polling‘]
        }

        this.sio = window.io.connect(url,opts);

        // 监听地城的系统事件
        this.sio.on(‘reconnect‘,function(){
            console.log(‘reconnection‘);
        });

        // 连接成功
        this.sio.on(‘connect‘,function(data){
            self.sio.connected = true;

            console.log("%%%%%%%%%%%%% connect");
            // 事件 + 数据名字
            self.send("your_echo","HelloWorld");
        });
        

        // 断开连接
        this.sio.on(‘disconnect‘,function(data){
            console.log("MMMMMdisconnect");
            self.sio.connected = false;
            // self.close();
        });
        
        // 连接失败
        this.sio.on(‘connect_failed‘,function (){
            console.log(‘connect_failed‘);
        });
        
        
        // 自己定义,如果你向要收那种事件的数据,你就监听这个事件
        this.sio.on(‘your_echo‘,function(data){
            console.log("your_echo",data);
        });
    },// 发送数据: 事件+数据的模型;
    send:function(event,data){
        if(this.sio.connected){
            this.sio.emit(event,data);  // 触发一个网络事件,名字 + 数据body ---> 服务器;              
        }
    },// 关闭socket
    close:function(){
        if(this.sio && this.sio.connected){
            this.sio.connected = false;
            this.sio.disconnect(); // API
            this.sio = null;
        }
    },};

module.exports = net;
// socket-io.js H5使用的io库文件,自行下载,需要添加判断!CC_JSB && !cc.sys.isNative
if (!CC_JSB && !cc.sys.isNative) {
  ...
  ...    
}
// game_scene.js 使用webscoket和socket.io的案例
var websocket = require("websocket");
var net = require("net");

cc.Class({
    extends: cc.Component,// use this for initialization
    onLoad: function () {
        net.connect("127.0.0.1:6081");
        // websocket.connect("ws://127.0.0.1:6080/ws");
    },on_server_client_comming);

// socketio
var socket_io = require(‘socket.io‘)
var sio = socket_io(6081);

sio.sockets.on(‘connection‘,function(data){
        console.log("disconnect");        
    });


});

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...