Skip to content

Commit

Permalink
Merge remote branch 'upstream/master' into ajaxorg
Browse files Browse the repository at this point in the history
Conflicts:
	lib/socket.io/listener.js
	support/socket.io-client/lib/socket.js
	support/socket.io-client/socket.io.js
  • Loading branch information
fjakobs committed Jan 4, 2011
2 parents a07502d + ffb0574 commit 66c4e10
Show file tree
Hide file tree
Showing 21 changed files with 1,111 additions and 977 deletions.
266 changes: 145 additions & 121 deletions History.md

Large diffs are not rendered by default.

74 changes: 39 additions & 35 deletions README.md
@@ -1,7 +1,7 @@
Socket.IO Server: Sockets for the rest of us
============================================

The `Socket.IO` server provides seamless supports for a variety of transports intended for realtime communication
The `Socket.IO` server provides seamless support for a variety of transports intended for realtime communication.

- WebSocket
- WebSocket over Flash (+ XML security policy support)
Expand All @@ -12,33 +12,35 @@ The `Socket.IO` server provides seamless supports for a variety of transports in

## Requirements

- Node v0.1.103+
- [Socket.IO client](http://github.com/LearnBoost/Socket.IO) to connect from the browser
- Node v0.1.103+ with `crypto` module support (make sure you have OpenSSL
headers when installing Node to get it)
- The [Socket.IO client](http://github.com/LearnBoost/Socket.IO), to connect from the browser

## How to use

To run the demo:
To run the demo, execute the following:

git clone git://github.com/LearnBoost/Socket.IO-node.git socket.io
cd socket.io/example/
sudo node server.js

and point your browser to http://localhost:8080. In addition to 8080, if the transport `flashsocket` is enabled, a server will be initialized to listen to requests on the port 843.
and point your browser to `http://localhost:8080`. In addition to `8080`, if the transport `flashsocket` is enabled, a server will be initialized to listen for requests on port `843`.

### Implementing it on your project

`Socket.IO` is designed not to take over an entire port or Node `http.Server` instance. This means that if you choose your HTTP server to listen on the port 80, `socket.io` can intercept requests directed to it and the normal requests will still be served.
`Socket.IO` is designed not to take over an entire port or Node `http.Server` instance. This means that if you choose to have your HTTP server listen on port `80`, `socket.io` can intercept requests directed to it, and normal requests will still be served.

By default, the server will intercept requests that contain `socket.io` in the path / resource part of the URI. You can change this (look at the available options below).
By default, the server will intercept requests that contain `socket.io` in the path / resource part of the URI. You can change this as shown in the available options below.

On the server:

var http = require('http'),
io = require('./path/to/socket.io'),
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();
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello world</h1>');
});

server.listen(80);
Expand All @@ -52,17 +54,18 @@ By default, the server will intercept requests that contain `socket.io` in the p
client.on('disconnect', function(){ … })
});

On the client side:
On the client:

<script src="/socket.io/socket.io.js"></script>
<script>
var socket = new io.Socket();
socket.connect();
socket.on('connect', function(){ … })
socket.on('message', function(){ … })
socket.on('disconnect', function(){ … })
</script>

The [client side](http://github.com/learnboost/socket.io) files will be served automatically by `Socket.IO-node`.
The [client-side](http://github.com/learnboost/socket.io) files are served automatically by `Socket.IO-node`.

## Documentation

Expand All @@ -76,15 +79,15 @@ Public Properties:

- *server*

The instance of _process.http.Server_
An instance of _process.http.Server_.

- *options*

The passed in options combined with the defaults
The passed-in options, combined with the defaults.

- *clients*

An object of clients indexed by their session ids.
An object of clients, indexed by session ID.

Methods:

Expand All @@ -94,30 +97,31 @@ Methods:

- *removeListener(event, λ)*

Remove a listener from the listener array for the specified event.
Removes 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.
Broadcasts a message to all clients. Optionally, you can pass a single session ID or array of session IDs to avoid broadcasting to, as the second argument.

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.
The resource is what allows the `socket.io` server to identify incoming connections from `socket.io` clients. Make sure they're in sync.

- *flashPolicyServer*

true
Create a Flash Policy file server on port 843 ( this is restricted port and you will need to have root permission ). If you disable the FlashPolicy file server Socket.io will automatically fall back to serving the policy file inline.
Create a Flash Policy file server on port `843` (this is restricted port and you will need to have root permission). If you disable the FlashPolicy file server, Socket.IO will automatically fall back to serving the policy file inline.

- *transports*

['websocket', 'server-events', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling']
['websocket', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling',
'jsonp-polling']
A list of the accepted transports.

Expand All @@ -129,21 +133,21 @@ Options:

ƒ(){ sys.log }
The logging function. Defaults to outputting to stdout through `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
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
Fired when a message from a client is received. Receives the message and Client instance as parameters.

- *clientDisconnect(client)*

Fired when a client is disconnected. Receives the Client instance as parameter
Fired when a client is disconnected. Receives the Client instance as a parameter.

Important note: `this` in the event listener refers to the `Listener` instance.

Expand All @@ -155,43 +159,43 @@ Public Properties:

- *listener*

The `Listener` instance this client belongs to.
The `Listener` instance to which this client belongs.

- *connected*

Whether the client is connected
Whether the client is connected.

- *connections*

Number of times the client connected
Number of times the client has connected.

Methods:

- *send(message)*

Sends a message to the client
Sends a message to the client.

- *broadcast(message)*

Sends a message to all other clients. Equivalent to Listener::broadcast(message, client.sessionId)
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:
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, consisting 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.
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 used for further communications exchanged between the client and 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 concept of session also naturally benefits a 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 reconnection.

The implementation of reconnection logic (potentially with retries) is left for the user. By default, transports that are keep-alive or open all the time (like WebSocket) have a timeout of 0 if a disconnection is detected.

* Message batching

In order to optimize the resources, messages are buffered. In the event of the server trying to send multiple messages while the client is temporarily disconnected (eg: xhr polling), messages are stacked, then encoded in a lightweight way and sent to the client whenever he becomes available.
Messages are buffered in order to optimize resources. In the event of the server trying to send multiple messages while a client is temporarily disconnected (eg: xhr polling), the messages are stacked and then encoded in a lightweight way, and sent to the client whenever it becomes available.

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.
Despite this extra layer, the messages are delivered unaltered to the various event listeners. You can `JSON.stringify()` objects, send XML, or even plain text.

## Credits

Expand Down Expand Up @@ -222,4 +226,4 @@ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2 changes: 1 addition & 1 deletion example/chat.html
Expand Up @@ -58,4 +58,4 @@ <h1>Sample chat client</h1>
</style>

</body>
</html>
</html>
107 changes: 53 additions & 54 deletions example/server.js
@@ -1,64 +1,63 @@
var http = require('http'),
url = require('url'),
fs = require('fs'),
io = require('../'),
sys = require('sys'),

/**
* Important note: this application is not suitable for benchmarks!
*/

var http = require('http')
, url = require('url')
, fs = require('fs')
, io = require('../')
, sys = require(process.binding('natives').util ? 'util' : 'sys')
, server;

server = http.createServer(function(req, res){
// your normal server code
var path = url.parse(req.url).pathname;
switch (path){
case '/':
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Welcome. Try the <a href="/chat.html">chat</a> example.</h1>');
res.end();
break;
case '/json.js':
case '/chat.html':
fs.readFile(__dirname + path, function(err, data){
if (err) return send404(res);
res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'})
res.write(data, 'utf8');
res.end();
});
break;
default: send404(res);
}
// your normal server code
var path = url.parse(req.url).pathname;
switch (path){
case '/':
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Welcome. Try the <a href="/chat.html">chat</a> example.</h1>');
res.end();
break;
case '/json.js':
case '/chat.html':
fs.readFile(__dirname + path, function(err, data){
if (err) return send404(res);
res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'})
res.write(data, 'utf8');
res.end();
});
break;
default: send404(res);
}
}),

send404 = function(res){
res.writeHead(404);
res.write('404');
res.end();
res.writeHead(404);
res.write('404');
res.end();
};

server.listen(8080, {
transportOptions: {
'xhr-polling': {
closeTimeout: 1000 * 60 * 5
}
}
});

server.listen(8080);

// socket.io, I choose you
// simplest chat application evar
var io = io.listen(server),
buffer = [];
var io = io.listen(server)
, buffer = [];
io.on('connection', function(client){
client.send({ buffer: buffer });
client.broadcast({ announcement: client.sessionId + ' connected' });

client.on('message', function(message){
var msg = { message: [client.sessionId, message] };
buffer.push(msg);
if (buffer.length > 15) buffer.shift();
client.broadcast(msg);
});
client.send({ buffer: buffer });
client.broadcast({ announcement: client.sessionId + ' connected' });
client.on('message', function(message){
var msg = { message: [client.sessionId, message] };
buffer.push(msg);
if (buffer.length > 15) buffer.shift();
client.broadcast(msg);
});

client.on('disconnect', function(){
client.broadcast({ announcement: client.sessionId + ' disconnected' });
});
});
client.on('disconnect', function(){
client.broadcast({ announcement: client.sessionId + ' disconnected' });
});
});
14 changes: 9 additions & 5 deletions lib/socket.io/client.js
Expand Up @@ -4,7 +4,8 @@ var urlparse = require('url').parse
, options = require('./utils').options
, encode = require('./utils').encode
, decode = require('./utils').decode
, merge = require('./utils').merge;
, merge = require('./utils').merge
, util = require(process.binding('natives').util ? 'util' : 'sys');

var Client = module.exports = function(listener, req, res, options, head){
process.EventEmitter.call(this);
Expand All @@ -22,7 +23,7 @@ var Client = module.exports = function(listener, req, res, options, head){
this._onConnect(req, res);
};

require('sys').inherits(Client, process.EventEmitter);
util.inherits(Client, process.EventEmitter);

Client.prototype.send = function(message){
if (!this._open || !(this.connection.readyState === 'open' || this.connection.readyState === 'writeOnly')){
Expand All @@ -47,7 +48,11 @@ Client.prototype._onMessage = function(data){
case '~h~':
return this._onHeartbeat(messages[i].substr(3));
case '~j~':
messages[i] = JSON.parse(messages[i].substr(3));
try {
messages[i] = JSON.parse(messages[i].substr(3));
} catch(e) {
messages[i] = {};
}
break;
}
this.emit('message', messages[i]);
Expand Down Expand Up @@ -160,7 +165,6 @@ Client.prototype._queue = function(message){
};

Client.prototype._generateSessionId = function(){
if (this.sessionId) return this.listener.options.log('This client already has a session id');
this.sessionId = Math.random().toString().substr(2);
return this;
};
Expand All @@ -181,4 +185,4 @@ Client.prototype._verifyOrigin = function(origin){
return false;
};

for (var i in options) Client.prototype[i] = options[i];
for (var i in options) Client.prototype[i] = options[i];

0 comments on commit 66c4e10

Please sign in to comment.