您的位置:首页 > Web前端 > Node.js

nodejs学习-socket.io

2016-03-20 00:42 363 查看
初学nodejs,抄了几个例子,发现有些代码有些不同,看源码解决疑惑/socket.io/socket,io.js/在哪socket.js->module.exports = Server;
function Server(srv, opts){
if (!(this instanceof Server)) return new Server(srv, opts);
if ('object' == typeof srv && !srv.listen) {
opts = srv;
srv = null;
}
opts = opts || {};
this.nsps = {};
this.path(opts.path || '/socket.io');
this.serveClient(false !== opts.serveClient);
this.adapter(opts.adapter || Adapter);
this.origins(opts.origins || '*:*');
this.sockets = this.of('/');
if (srv) this.attach(srv, opts);
}
API摘自Readme.mdServer()Server(opts:object)Server(portLNumber:opts:object)Server(src:httpServer[,opts:object]):opts:serverClient:请求/socket.io/socket.io.js时返回文件默认true:var clientSource = read(require.resolve('socket.io-client/socket.io.js'), 'utf-8')path:var url = this._path + '/socket.io.js';  请求/socket.io/socket.io.js匹配adapter:origin:<function serverClient(v:boolear):同opts.serverClientfunction path(v:string);同opts.path socket.io.js:module.expots = lookupexports.connect = lookup;-> io(url) 和 io.connect(url) 效果相同io.on("connect")io.sockets.on("connection")-->Server(src,opts){..codethis.attach(src,opts);}-->Server.prototype.attach = function(srv, opts){..codethis.bind(this.eio)return this}-->Server.prototype.bind = function(engine){  this.engine = engine;  this.engine.on('connection', this.onconnection.bind(this));  return this;};-->Server.prototype.onconnection = function(conn){  debug('incoming connection with id %s', conn.id);  var client = new Client(this, conn);  client.connect('/');  return this;};-->client.connect-->namespace.add()->socket.join)-->(room)adaper.add()-->Namespace.prototype.add
self.emit('connect', socket);self.emit('connection', socket);
function lookup(url,opts){...codereturn io.socket(parsed,path);}创建socketManager.prototype.socket = function(nsp){ var socket = this.nsps[nsp];  if (!socket) {    socket = new Socket(this, nsp);...code}socket.jsfunction Socket(io, nsp){  this.io = io;  this.nsp = nsp;  this.json = this; // compat  this.ids = 0;  this.acks = {};  this.receiveBuffer = [];  this.sendBuffer = [];  this.connected = false;  this.disconnected = true;  if (this.io.autoConnect) this.open();}Manager.prototype.connect = function(fn){..code}-->onopen()emit('connect");...server部分:
  var socket = require('socket.io-client')('http://localhost');socket.on('connect', function(){});socket.on('event', function(data){});socket.on('disconnect', function(){});
client部分:
<script src="/socket.io/socket.io.js"></script><script>var socket = io('http://localhost');socket.on('connect', function(){});socket.on('event', function(data){});socket.on('disconnect', function(){});</script>
//to do
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: