Socket.IO
Introduction
Socket.IO aims to provide a really simple API to leverage Sockets in the client side. It hides the complexity of the different transport mechanisms used to achieve realtime communication between a browser and a server today.
How to use
io.setPath('/path/to/socket.io/'); socket = new io.Socket('localhost'); socket.connect(); socket.send('some data'); socket.addEvent('message', function(data){ alert('got some data' + data); });
Features
Supports
- WebSocket
- Adobe Flash Socket
- ActiveX HTMLFile (IE)
- Server-Sent Events (Opera)
- XHR with multipart encoding
- XHR with long-polling
ActionScript Socket is known not to work behind proxies, as it doesn't have access to the user agent proxy settings to implement the CONNECT HTTP method. If it fails,
socket.io
will try something else.On a successful connection, it remembers the transport for next time (stores it in a cookie).
Small. Closure Compiled with all deps: 5.82kb (gzipped).
Easy to use!
Documentation
io.Socket
new io.Socket(host, [options]);
Options:
The resource is what allows the socket.io
server to identify incoming connections by socket.io
clients. In other words, any HTTP server can implement socket.io and still serve other normal, non-realtime HTTP requests.
transports
['websocket', 'server-events', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling']
A list of the transports to attempt to utilize (in order of preference)
transportOptions
{ someTransport: { someOption: true }, ... }
An object containing (optional) options to pass to each transport.
Properties:
options
The passed in options combined with the defaults
connected
Whether the socket is connected or not.
connecting
Whether the socket is connecting or not.
transport
The transport instance.
Methods:
connect
Establishes a connection
send(message)
A string of data to send.
disconnect
Closes the connection
addEvent(event, λ)
Adds a listener for the event event
removeEvent(event, λ)
Removes the listener λ for the event event
Events:
connect
Fired when the connection is established and the handshake successful
message(message)
Fired when a message arrives from the server
close
Fired when the connection is closed. Be careful with using this event, as some transports will fire it even under temporary, expected disconnections (such as XHR-Polling).
disconnect
Fired when the connection is considered disconnected.
Socket.IO Node.JS server
How to use
var http = require('http'), io = require('./socket.io/socket.io.js'), server = http.createServer(function(req, res){ // your normal server code res.writeHeader(200, {'Content-Type': 'text/html'}); res.writeBody('<h1>Hello world</h1>'); res.finish(); }); // socket.io, I choose you io.listen(server);
Documentation
Listener
io.listen(<http.Server>, [options])
Returns: a Listener
instance
Public Properties:
server
The instance of process.http.Server
options
The passed in options combined with the defaults
clients
An array of clients. Important: disconnected clients are set to null, the array is not spliced.
clientsIndex
An object of clients indexed by their session ids.
Methods:
addListener(event, λ)
Adds a listener for the specified event. Optionally, you can pass it as an option to
io.listen
, prefixed byon
. For example:onClientConnect: function(){}
removeListener(event, λ)
Remove a listener from the listener array for the specified event.
broadcast(message, [except])
Broadcasts a message to all clients. There's an optional second argument which is an array of session ids or a single session id to avoid broadcasting to.
Options:
resource
socket.io
The resource is what allows the socket.io
server to identify incoming connections by socket.io
clients. Make sure they're in sync.
transports
['websocket', 'server-events', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling']
A list of the accepted transports.
timeout
8000
Time it has to pass without a reconnection to consider a client disconnected. Applies to all transports.
log
ƒ(){ sys.log }
The logging function. Defaults to outputting to stdout through
sys.log
Events:
clientConnect(client)
Fired when a client is connected. Receives the Client instance as parameter
clientMessage(message, client)
Fired when a message from a client is received. Receives the message and Client instance as parameter
clientDisconnect(client)
Fired when a client is disconnected. Receives the Client instance as parameter
Important note: this
in the event listener refers to the Listener
instance.
Client
Client(listener, req, res)
Public Properties:
listener
The
Listener
instance this client belongs to.connected
Whether the client is connected
connections
Number of times the client connected
Methods:
send(message)
Sends a message to the client
broadcast(message)
Sends a message to all other clients. Equivalent to Listener::broadcast(message, client.sessionId)
Protocol
One of the design goals is that you should be able to implement whatever protocol you desire without Socket.IO
getting in the way. Socket.IO
has a minimal, unobtrusive protocol layer. It consists of two parts:
Connection handshake
This is required to simulate a full duplex socket with transports such as XHR Polling or Server-sent Events (which is a "one-way socket"). The basic idea is that the first message received from the server will be a JSON object that contains a session id that will be used for further communication exchanged between the client and the server.
The concept of session also benefits naturally full-duplex WebSocket, in the event of an accidental disconnection and a quick reconnection. Messages that the server intends to deliver to the client are cached temporarily until the reconnection.
The implementation of reconnection logic (potentially with retries) is left for the user.
Message batching
In order to optimize the resources, messages are batched. In the event of the server trying to send multiple messages while the client is temporarily disconnected (ie: xhr polling), and messages are stacked, or messages being stacked prior to the handshake being successful, a JSON object containing a list (array) of messages is sent to the client.
Despite this extra layer, your messages are delivered unaltered to the different event listeners. You can JSON.stringify() objects, send XML, or maybe plain text.
Aucun commentaire:
Enregistrer un commentaire