socket.io学习笔记1(转载)

socket.io学习笔记一(转载)

细节问题

  • 浏览器端socket.io文件加载
<script src="/socket.io/socket.io.js"></script>

官方示例,令人迷惑。查阅得知,socket.io 库会拦截/socket.io开始的所有路径,当做普通http请求进行响应,返回文件需要经过服务器端处理,我用浏览器保存了一份http://snowykiss.qiniudn.com/socket.io.js,方便查阅。

  • 命名空间
    假设服务器地址为http://127.0.0.1
var io = require('socket.io').listen(1338);
io.sockets.on('connection', function (socket) {
    socket.on('test', function (data) {
        socket.broadcast.emit('love',{'title' : 'I LOVE you forever...'
           ,'reason' : 'unbelieve'
        });
    });
});
var socket = io.connect('http://127.0.0.1:1338')
socket.on('love',function(data){
   console.log(data);
})

这里的broadcast会向其它所有连接到此端口的client side发送消息.

var io = require('socket.io').listen(1338);
io.of('/some').on('connection', function (socket) {
    socket.on('test', function (data) {
        socket.broadcast.emit('love',{'title' : 'I LOVE you forever...'
            ,'reason' : 'unbelieve'
        });
    });
});
var socket = io.connect('http://127.0.0.1:1338/some')
socket.on('love',function(data){
   console.log(data);
})

这里的broadcast只会向url参数为http://127.0.0.1:1338/some发送消息,虽然所有的连接都是websocket--http://127.0.0.1:1338/的连接。

  • 如果不想使用自定义事件,通过socket.emit('customEvent',data)的方式推送消息,官方支持socket.send()方法。服务器端通过socket.on('message',function(data){}),浏览器端同样通过socket.on('message',function(data){})获取数据,注意这是预置的事件。

  • Worker模式
    不知道websocket对浏览器的压力是否过大,如果担心websocket进程压力,可以启用worker模式,不过需要将socket.io事件封 装方式,通过worker.postMessage()配合Worker message Event重新封装一遍,感觉挺鸡肋。

importScripts('socket.io.js');

var socket = io.connect('http://127.0.0.1:1338/');
var self = this;
socket.on('butterfly',function(data){
    self.postMessage({"name" : "butterfly","data" : data});
});
socket.on('love',function(data){
     self.postMessage({"name" : "love","data" : data});
}) 

下面是我用Worker微扩展测试,声明新的Worker对象后,就可以监听自定义伪事件,跟socket.io保持同步的on方法,其它伪事件监听应该相似,不做衍生说明

Worker.prototype.reg = {};
Worker.prototype.on = function (event,fn) {
    if (!this.reg[event]) {
      this.reg[event] = fn;
    } else if (typeof(this.reg[event]) == 'array') {
      this.reg[event].push(fn);
    } else {
      this.reg[event] = [this.reg[event], fn];
    }
};
var story = new Worker('lover.js');
story.on('love',function(e){
       console.log(e.data);
})
story.addEventListener('message', function (e) {
    if(e.data.name){
        this.reg[e.data.name].call(this, e.data);
    }
});
原文地址:http://segmentfault.com/blog/bornkiller/1190000000427074