gevent-socketio
2014-09-11 09:48
204 查看
https://github.com/abourget/gevent-socketiohttps://github.com/Automattic/socket.io
Presentation
gevent-socketio is a Python implementation of the Socket.IO protocol, developed originally for Node.js by LearnBoostand then ported to other languages. Socket.IO enables real-time web communications between a browser and a server, using a WebSocket-like API. One aim of this project is to provide a single gevent-basedAPI that works across the different WSGI-based web frameworks out there (Pyramid, Pylons, Flask, web2py, Django, etc...). Only ~3 lines of code are required to tie-in gevent-socketio inyour framework. Note: you need to use the gevent python WSGI server to use gevent-socketio.Technicaloverview
Most of the gevent-socketio implementation is pure Python. There is an obvious dependency ongevent,and another on gevent-websocket. There are integration examples for Pyramid, Flask, Django and BYOF (bring yourown framework!).Documentationand References
You can read the renderered Sphinx docs at:http://readthedocs.org/docs/gevent-socketio/en/latest/Discussion and questions happen on the mailing list:https://groups.google.com/forum/#!forum/gevent-socketioor in the Github issue tracking:https://github.com/abourget/gevent-socketio/issuesYou can also contact the maintainer:https://twitter.com/#!/bourgetalexndrehttps://plus.google.com/109333785244622657612Installation
You can install with standard Python methods:pip install gevent-socketioor from source:
git clone git://github.com/abourget/gevent-socketio.git cd gevent-socketio python setup.py installFor development, run instead of install:
python setup.py developIf you want to do all of that in a virtualenv, run:
virtualenv env . env/bin/activate python setup.py develop # or install
.var server = require('http').Server();var io = require('socket.io')(server);io.on('connection', function(socket){socket.on('event', function(data){});socket.on('disconnect', function(){});});server.listen(3000);[/code]socket.io
How to use
The following example attaches socket.io to a plain Node.JS HTTP server listening on port [code]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 tohttpor
http
Serverinstances. You need to pass the
Serverto
socket.io, and not the express application function.
var app = require('express')();var server = require('http').Server(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 thecallbackmethod.
var app = require('koa')();var server = require('http').Server(app.callback());var io = require('socket.io')(server);io.on('connection', function(){ /* … */ });server.listen(3000);
API
Server
Exposed byrequire('socket.io').
Server()
Creates a newServer. Works with and without
new:
var io = require('socket.io')();// orvar Server = require('socket.io');var io = new Server();
Server(opts:Object)
Optionally, the first or second argument (see below) of theServerconstructor can be an options object.The following options are supported:
serveClientsets the value for Server#serveClient()
pathsets the value for Server#path()The same options passed to socket.io are always passed to the
engine.io
Serverthat gets created. See engine.io options as reference.
Server(srv:http#Server, opts:Object)
Creates a newServerand attaches it to the given
srv. Optionally
optscan be passed.
Server(port:Number, opts:Object)
Binds socket.io to a newhttp.Serverthat listens on
port.
Server#serveClient(v:Boolean):Server
Ifvis
truethe attached server (see
Server#attach) will serve the client files. Defaults to
true.This method has no effect after
attachis called.
// pass a server and the `serveClient` optionvar io = require('socket.io')(http, { serveClient: false });// or pass no server and then you can call the methodvar 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 pathvunder which
engine.ioand 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 adapterv. Defaults to an instance of the
Adapterthat 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 originsv. Defaults to any origins being allowed.If no arguments are supplied this method returns the current value.
Server#sockets:Namespace
The default (/) namespace.
Server#attach(srv:http#Server, opts:Object):Server
Attaches theServerto an engine.io instance on
srvwith the supplied
opts(optionally).
Server#attach(port:Number, opts:Object):Server
Attaches theServerto an engine.io instance that is bound to
portwith the given
opts(optionally).
Server#listen
Synonym ofServer#attach.
Server#bind(srv:engine#Server):Server
Advanced use only. Binds the server to a specific engine.ioServer(or compatible API) instance.
Server#onconnection(socket:engine#Socket):Server
Advanced use only. Creates a newsocket.ioclient from the incoming engine.io (or compatible API)
socket.
Server#of(nsp:String):Namespace
Initializes and retrieves the givenNamespaceby 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
Namespacebelow.
Server#close
Closes socket servervar io = require('socket.io');var PORT = 3030;var server = require('http').Server();io(PORT);io.close(); // Close current serverserver.listen(PORT); // PORT is free to useio(server);
Server#use
SeeNamespace#usebelow.
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:
Socketthe incoming socket.
Namespace#name:String
The namespace identifier property.Namespace#connected:Object
Hash ofSocketobjects 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 incomingSocketand 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
errorpackets to clients.
Socket
ASocketis the fundamental class for interacting with browser clients. A
Socketbelongs to a certain
Namespace(by default
/) and uses an underlying
Clientto communicate.
Socket#rooms:Array
A list of strings identifying the rooms this socket is in.Socket#client:Client
A reference to the underlyingClientobject.
Socket#conn:Socket
A reference to the underylingClienttransport connection (engine.io
Socketobject).
Socket#request:Request
A getter proxy that returns the reference to therequestthat originated the underlying engine.io
Client. Useful for accessing request headers such as
Cookieor
User-Agent.
Socket#id:String
A unique identifier for the socket session, that comes from the underlyingClient.
Socket#emit(name:String[, …]):Socket
Emits an event to the socket identified by the stringname. 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 theroom, and fires optionally a callback
fnwith
errsignature (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
Adapterthat has been configured (see
Server#adapterabove), defaulting to socket.io-adapter.
Socket#leave(name:String[, fn:Function]):Socket
Removes the socket fromroom, and fires optionally a callback
fnwith
errsignature (if any).Rooms are left automatically upon disconnection.The mechanics of leaving rooms are handled by the
Adapterthat has been configured (see
Server#adapterabove), 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 givenroom.To emit to multiple rooms, you can call
toseveral times.
var io = require('socket.io')();io.on('connection', function(socket){socket.to('others').emit('an event', { some: 'data' });});
Client
TheClientclass represents an incoming transport (engine.io) connection. A
Clientcan be associated with many multiplexed
Socketthat belong to different
Namespaces.
Client#conn
A reference to the underlyingengine.io
Socketconnection.
Client#request
A getter proxy that returns the reference to therequestthat originated the engine.io connection. Useful for accessing request headers such as
Cookieor
User-Agent.
Debug / logging
Socket.IO is powered by debug. In order to see all the debug output, run your app with the environment variableDEBUGincluding the desired scope.To see the output from all of Socket.IO's debugging scopes you can use:
DEBUG=socket.io* node myapp
License
MIT相关文章推荐
- Gevent-Socketio Module-Socketio
- Gevent-socketio documentation — gevent-socketio 0.3.1 documentation
- Gevent-socketio文档-Socket.IO的一个python实现
- Nodejs npm安装socket.io报错解决办法
- HTML5之WebSocket入门3 -通信模型socket.io
- 使用Node.js+Socket.IO搭建WebSocket实时应用
- 使用React、Node.js、MongoDB、Socket.IO开发一个角色投票应用的学习过程(一)
- socketio
- Socket.io创建连接的参数
- Socket.IO:支持WebSocket协议、用于实时通信和跨平台的框架
- node.js 之 socket.io
- Windows Socket IO 模型
- socketio的应用
- 很幽默的讲解六种Socket IO模型(转)
- Web实时通信之Socket.IO
- Node.js笔记(三)路由和socket.io
- 使用Node.js+Socket.IO搭建WebSocket实时应用
- GO语言 --socket.io
- <srcipt src="/socket.io/socket.io.js"></script>加载的资源是从哪儿冒出来的?
- node.js+socket.io配置详解