1. 程式人生 > >cocos creator WebSocket與 node.js ws通訊

cocos creator WebSocket與 node.js ws通訊

1)服務端

var ws = require("ws");

var server = new ws.Server({
    port: 6080
});

server.on("connection", function (session) {
    session.on("close", function () {
        
    });

    session.on("error", function (err) {

    });

    session.on("message", function (data) {
        console.log("server rcv data=" + data);

        session.send(data);
    });
});

2)客戶端

websocket.js封裝

var websocket = {
    sock: null,

    on_open: function () {
        this.send_data(JSON.stringify({
            stype: "auth",
            ctype: "login",
            data: {
                name: "jianan",
                pwd: 123456
            }
        }));
    },
    
    on_message: function (event) {
        console.log("client rcv data=" + event.data);
    },

    on_close: function () {
        this.close();
    },

    on_error: function () {
        this.close();
    },
    
    close: function () {
        if(this.sock){
            this.sock.close();
            this.sock = null;
        }
    },

    connect: function (url) {
        this.sock = new WebSocket(url);
        this.sock.binaryType = "arraybuffer";
        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);
    },

    send_data: function (data) {
        this.sock.send(data);
    }

}

module.exports = websocket;

連線伺服器

var websocket = require("./websocket.js");

cc.Class({
    extends: cc.Component,

    properties: {

    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {
        websocket.connect("ws://127.0.0.1:6080/ws");
    },

    // update (dt) {},
});

 

 

socket.io則注意事項略多,需要客戶端伺服器版本號一致,容易出問題。 推薦使用websocket,而不要使用socket.io