1)node.js服务端ws模块
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;
cocos creator客户端连接node.js服务器(此处通信用json协议)
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 !!!