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的粘包現象

客戶端代碼html

// 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) {

    // },
});

服務器代碼node

// 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();

客戶端代碼web

// 導出的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"); }); });
相關文章
相關標籤/搜索