zoukankan      html  css  js  c++  java
  • 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见服务器课程;

    TCP的粘包现象

    客户端代码

    // 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, // optional, default is true
            //    visible: true,      // optional, default is true
            //    displayName: 'Foo', // optional
            //    readonly: false,    // optional, 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,
    
        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, // optional, default is true
            //    visible: true,      // optional, default is true
            //    displayName: 'Foo', // optional
            //    readonly: false,    // optional, 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);
    
    // socketio
    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");        
        });
    
    
    });
  • 相关阅读:
    重新想象 Windows 8 Store Apps (15) 控件 UI: 字体继承, Style, ControlTemplate, SystemResource, VisualState, VisualStateManager
    重新想象 Windows 8 Store Apps (12) 控件之 GridView 特性: 拖动项, 项尺寸可变, 分组显示
    返璞归真 asp.net mvc (10) asp.net mvc 4.0 新特性之 Web API
    与众不同 windows phone (29) Communication(通信)之与 OData 服务通信
    与众不同 windows phone (33) Communication(通信)之源特定组播 SSM(Source Specific Multicast)
    与众不同 windows phone (27) Feature(特性)之搜索的可扩展性, 程序的生命周期和页面的生命周期, 页面导航, 系统状态栏
    与众不同 windows phone (30) Communication(通信)之基于 Socket TCP 开发一个多人聊天室
    返璞归真 asp.net mvc (12) asp.net mvc 4.0 新特性之移动特性
    重新想象 Windows 8 Store Apps (2) 控件之按钮控件: Button, HyperlinkButton, RepeatButton, ToggleButton, RadioButton, CheckBox, ToggleSwitch
    重新想象 Windows 8 Store Apps (10) 控件之 ScrollViewer 特性: Chaining, Rail, Inertia, Snap, Zoom
  • 原文地址:https://www.cnblogs.com/orxx/p/10547445.html
Copyright © 2011-2022 走看看