文档章节

socket.io

短短的歼击机
 短短的歼击机
发布于 2014/09/25 10:42
字数 1317
阅读 701
收藏 4
How to use


The following example attaches socket.io to a plain Node.JS HTTP server listening on port 3000.


var server = require('http').createServer();
var io = require('socket.io')(server);
io.on('connection', function(socket){
  socket.on('event', function(data){});
  socket.on('disconnect', function(){});
});
server.listen(3000);
Standalone


var io = require('socket.io')();
io.on('connection', function(socket){});
io.listen(3000);
In conjunction with Express


Starting with 3.0, express applications have become request handler functions that you pass to http or http Server instances. You need to pass the Server to socket.io, and not the express application function.


var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(){ /* … */ });
server.listen(3000);
In conjunction with Koa


Like Express.JS, Koa works by exposing an application as a request handler function, but only by calling the callback method.


var app = require('koa')();
var server = require('http').createServer(app.callback());
var io = require('socket.io')(server);
io.on('connection', function(){ /* … */ });
server.listen(3000);
API


Server


Exposed by require('socket.io').


Server()


Creates a new Server. Works with and without new:


  var io = require('socket.io')();
  // or
  var Server = require('socket.io');
  var io = new Server();
Server(opts:Object)


Optionally, the first or second argument (see below) of the Server constructor can be an options object.


The following options are supported:


serveClient sets the value for Server#serveClient()
path sets the value for Server#path()


The same options passed to socket.io are always passed to the engine.io Server that gets created. See engine.io options as reference.


Server(srv:http#Server, opts:Object)


Creates a new Server and attaches it to the given srv. Optionally opts can be passed.


Server(port:Number, opts:Object)


Binds socket.io to a new http.Server that listens on port.


Server#serveClient(v:Boolean):Server


If v is true the attached server (see Server#attach) will serve the client files. Defaults to true.


This method has no effect after attach is called.


  // pass a server and the `serveClient` option
  var io = require('socket.io')(http, { serveClient: false });


  // or pass no server and then you can call the method
  var io = require('socket.io')();
  io.serveClient(false);
  io.attach(http);
If no arguments are supplied this method returns the current value.


Server#path(v:String):Server


Sets the path v under which engine.io and the static files will be served. Defaults to /socket.io.


If no arguments are supplied this method returns the current value.


Server#adapter(v:Adapter):Server


Sets the adapter v. Defaults to an instance of the Adapter that ships with socket.io which is memory based. See socket.io-adapter.


If no arguments are supplied this method returns the current value.


Server#origins(v:String):Server


Sets the allowed origins v. Defaults to any origins being allowed.


If no arguments are supplied this method returns the current value.


Server#origins(v:Function):Server


Sets the allowed origins as dynamic function. Function takes two arguments origin:String and callback(error, success), where success is a boolean value indicating whether origin is allowed or not.


Potential drawbacks:


in some situations, when it is not possible to determine origin it may have value of *
As this function will be executed for every request, it is advised to make this function work as fast as possible
If socket.io is used together with Express, the CORS headers will be affected only for socket.io requests. For Express can use cors
Server#sockets:Namespace


The default (/) namespace.


Server#attach(srv:http#Server, opts:Object):Server


Attaches the Server to an engine.io instance on srv with the supplied opts (optionally).


Server#attach(port:Number, opts:Object):Server


Attaches the Server to an engine.io instance that is bound to port with the given opts (optionally).


Server#listen


Synonym of Server#attach.


Server#bind(srv:engine#Server):Server


Advanced use only. Binds the server to a specific engine.io Server (or compatible API) instance.


Server#onconnection(socket:engine#Socket):Server


Advanced use only. Creates a new socket.io client from the incoming engine.io (or compatible API) socket.


Server#of(nsp:String):Namespace


Initializes and retrieves the given Namespace by its pathname identifier nsp.


If the namespace was already initialized it returns it right away.


Server#emit


Emits an event to all connected clients. The following two are equivalent:


  var io = require('socket.io')();
  io.sockets.emit('an event sent to all connected clients');
  io.emit('an event sent to all connected clients');
For other available methods, see Namespace below.


Server#close


Closes socket server


  var io     = require('socket.io');
  var PORT   = 3030;
  var server = require('http').Server();


  io(PORT);


  io.close(); // Close current server


  server.listen(PORT); // PORT is free to use


  io(server);
Server#use


See Namespace#use below.


Namespace


Represents a pool of sockets connected under a given scope identified by a pathname (eg: /chat).


By default the client always connects to /.


Events


connection / connect. Fired upon a connection.


Parameters:


Socket the incoming socket.
Namespace#name:String


The namespace identifier property.


Namespace#connected:Object


Hash of Socket objects that are connected to this namespace indexed by id.


Namespace#use(fn:Function):Namespace


Registers a middleware, which is a function that gets executed for every incoming Socket and receives as parameter the socket and a function to optionally defer execution to the next registered middleware.


  var io = require('socket.io')();
  io.use(function(socket, next){
    if (socket.request.headers.cookie) return next();
    next(new Error('Authentication error'));
  });
Errors passed to middleware callbacks are sent as special error packets to clients.


Socket


A Socket is the fundamental class for interacting with browser clients. A Socket belongs to a certain Namespace (by default /) and uses an underlying Client to communicate.


Socket#rooms:Array


A list of strings identifying the rooms this socket is in.


Socket#client:Client


A reference to the underlying Client object.


Socket#conn:Socket


A reference to the underyling Client transport connection (engine.io Socket object).


Socket#request:Request


A getter proxy that returns the reference to the request that originated the underlying engine.io Client. Useful for accessing request headers such as Cookie or User-Agent.


Socket#id:String


A unique identifier for the socket session, that comes from the underlying Client.


Socket#emit(name:String[, …]):Socket


Emits an event to the socket identified by the string name. Any other parameters can be included.


All datastructures are supported, including Buffer. JavaScript functions can't be serialized/deserialized.


  var io = require('socket.io')();
  io.on('connection', function(socket){
    socket.emit('an event', { some: 'data' });
  });
Socket#join(name:String[, fn:Function]):Socket


Adds the socket to the room, and fires optionally a callback fn with err signature (if any).


The socket is automatically a member of a room identified with its session id (see Socket#id).


The mechanics of joining rooms are handled by the Adapter that has been configured (see Server#adapter above), defaulting to socket.io-adapter.


Socket#leave(name:String[, fn:Function]):Socket


Removes the socket from room, and fires optionally a callback fn with err signature (if any).


Rooms are left automatically upon disconnection.


The mechanics of leaving rooms are handled by the Adapter that has been configured (see Server#adapter above), defaulting to socket.io-adapter.


Socket#to(room:String):Socket


Socket#in(room:String):Socket


Sets a modifier for a subsequent event emission that the event will only be broadcasted to sockets that have joined the given room.


To emit to multiple rooms, you can call to several times.


  var io = require('socket.io')();
  io.on('connection', function(socket){
    socket.to('others').emit('an event', { some: 'data' });
  });
Client


The Client class represents an incoming transport (engine.io) connection. A Client can be associated with many multiplexed Socket that belong to different Namespaces.


Client#conn


A reference to the underlying engine.io Socket connection.


Client#request


A getter proxy that returns the reference to the request that originated the engine.io connection. Useful for accessing request headers such as Cookie or User-Agent.


Debug / logging


Socket.IO is powered by debug. In order to see all the debug output, run your app with the environment variable DEBUG including the desired scope.


To see the output from all of Socket.IO's debugging scopes you can use:


DEBUG=socket.io* node myapp

© 著作权归作者所有

短短的歼击机

短短的歼击机

粉丝 82
博文 268
码字总数 269797
作品 0
武汉
高级程序员
私信 提问
npm install socket.io

正确安装nodejs后,再安装socket.io; 用的npm install socket.io命令 以下是报错 C:\Program Files\nodejs>npm install socket.io - > ws@0.5.0 install C:\Program Files\nodejs\node_modu......

wklc2014
2015/06/01
4.5K
6
基于Node.js的socket.io机制的陷阱,仅针对于客户端继承socket.io的问题的解决方案

Socket.IO enables real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed. 众所周时 Socket.I......

起始页
2015/03/13
0
0
Socket.IO for Erlang

Socket.IO 旨在让各种浏览器与移动设备上实现实时app功能,模糊化各种传输机制。 而 Socket.IO-erlang 是 Socket.IO 的 Erlang 语言的完整实现,完全兼容 Socket.IO。...

匿名
2012/06/24
2K
0
手机端与网页通过websocket通信

手机端与网页通讯,使用websocket完成二者之间的联通。 websocket选用socket.io类实现。 服务器端,使用nodejs,代码依赖了express和socket.io。 首先建立一个http服务器 var app = require(...

yige2002
2017/04/29
0
0
socket.io 实现在线聊天室

效果图.gif websocket工作机制 WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。websocket链接建立后,服务...

TokenYang
2017/11/13
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Centos7 python2.7和yum完全卸载及重装

                                     完全重装python和yum 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 1、删除现有...

roockee
35分钟前
6
0
【软件工程】绪论,深入浅出理解软件工程

软件和软件工程 什么是软件工程 软件工程是贯穿整个软件生命周期的工程学和方法论及其使用的工具(我说的) 软件工程要解决那些问题 软件的研发周期过长 软件开发成本居高不下 软件在交付之前...

丌官尚雄
42分钟前
7
0
无回路有向图的拓扑排序

因公司业务需要,在表单中每个字段都会配置自动计算,但自动计算公式中会引用到其他字段中的值。所以希望可以根据计算公式,优先计算引用的公式。所以最终使用了无回路有向图的扩扑排序来实现...

兜兜毛毛
今天
7
0
如何抢占云栖大会C位?史上最强强强攻略来了

点击观看视频: APSARA云栖大会开发者情怀 原文链接 本文为云栖社区原创内容,未经允许不得转载。

阿里云官方博客
今天
6
0
Kubernetes 从懵圈到熟练:集群服务的三个要点和一种实现

作者 | 声东 阿里云售后技术专家 文章来源:Docker,点击查看原文。 以我的经验来讲,理解 Kubernetes 集群服务的概念,是比较不容易的一件事情。尤其是当我们基于似是而非的理解,去排查服务...

阿里巴巴云原生
今天
12
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部