cocos creator socket.io 与 node.js socket.io通信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/themagickeyjianan/article/details/86107941

1)客户端

if (window.io == null){
    window.io = require("./3rd/socket-io.js");
}

var socketio = {
    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("connected!!!");

            self.send("your_echo", JSON.stringify({
                stype: "auth",
                ctype: "login",
                data: {
                    name: "jianan",
                    pwd: 123456
                }
            }))
        });

        //
        this.sio.on("disconnect", function () {
            console.log("disconnect");

            self.sio.connected = false;
        });

        //
        this.sio.on("connect_failed", function () {
            console.log("connect_failed");

            self.sio.connected = false;
        });

        
        //
        this.sio.on("your_echo", function (data) {
            console.log("client rcv data=" + data);
        });
    },
    
    send: function (event, data) {
        if(this.sio.connected){
            this.sio.emit(event, data);
        }
    },
    
    close: function () {
        if(this.sio && this.sio.connected){
            this.sio.connected = false;
            this.sio.disconnect();
            this.sio = null;
        }
    }
}

module.exports = socketio;
var socketio = require("./socketio.js");

cc.Class({
    extends: cc.Component,

    properties: {

    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

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

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

需要特别注意的是:客户端引入的这个第三方的socket.io模块版本一定要和npm安装的服务器的socket.io一致才行,否则可能出现连不上的情况。 而使用websocket,一般客户端已经封装好了这个模块,因此更为简单一点。 推荐使用websocket而不是socket.io

2)服务器

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

sio.sockets.on("connection", function (socket) {
    console.log("client coming");

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

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

    socket.on("disconnect", function (data) {
        console.log("disconnect");
    });
});

猜你喜欢

转载自blog.csdn.net/themagickeyjianan/article/details/86107941
今日推荐