Compare commits

...

825 Commits
0.9.5 ... 2.0.2

Author SHA1 Message Date
Damien Arrachequesne
a10dc8d92d [chore] Release 2.0.2 2017-06-01 14:01:24 +02:00
Damien Arrachequesne
2b216902e1 [fix] Fix timing issues with middleware (#2948)
Using a middleware could previously lead to a connecting client
receiving a connect event from the server before the server triggers
its own connect event.
2017-05-22 13:01:59 +02:00
Damien Arrachequesne
832b8fc6d9 [chore] Release 2.0.1 2017-05-09 01:40:46 +02:00
Damien Arrachequesne
a0056904c1 [fix] Update path of client file (#2934) 2017-05-09 01:36:40 +02:00
Damien Arrachequesne
3367eaa948 [chore] Release 2.0.0 2017-05-09 01:09:19 +02:00
Damien Arrachequesne
6c0705f733 [docs] Add an example of custom parser (#2929) 2017-05-09 00:46:01 +02:00
Damien Arrachequesne
1980fb4a03 [chore] Merge history of 1.7.x and 0.9.x branches (#2930) 2017-05-09 00:45:17 +02:00
Xavier Damman
0d07c47f81 [chore] Added backers and sponsors on the README (#2933) 2017-05-09 00:41:46 +02:00
Damien Arrachequesne
a086588747 [chore] Bump dependencies (#2926) 2017-04-28 22:33:40 +02:00
Damien Arrachequesne
87b06ad362 [feat] Move binary detection to the parser (#2923) 2017-04-25 00:38:07 +02:00
Caleb
199eec648e [docs] Replace non-breaking space with proper whitespace (#2913) 2017-04-19 22:19:57 +02:00
Faraz Patankar
f1b39a6b1d [docs] Update emit cheatsheet (#2906) 2017-04-03 07:20:38 +02:00
Damien Arrachequesne
240b154960 [docs] Explicitly document that Server extends EventEmitter (#2874) 2017-03-29 14:13:04 +02:00
efkan
c5b7738730 [docs] Add server.engine.generateId attribute (#2880) 2017-03-29 13:52:07 +02:00
Simen Bekkhus
03f3bc9ab3 [docs] Fix wrong space character in README (#2900) 2017-03-27 13:15:19 +02:00
SwhGo_oN
e40accf7a1 [docs] Fix documentation for 'connect' event (#2898) 2017-03-19 00:33:59 +01:00
Damien Arrachequesne
01a4623613 [feat] Allow to join several rooms at once (#2879) 2017-02-26 09:15:32 +01:00
Damien Arrachequesne
2d5b0026c5 [docs] Add webpack build example (#2828) 2017-02-22 12:48:46 +01:00
Damien Arrachequesne
5ae06e6285 [chore] Bump socket.io-adapter to version 1.0.0 (#2867) 2017-02-17 07:33:43 +01:00
sgress454
4d8f68c7dc [chore] Bump engine.io to version 2.0.2 (#2864)
Includes the following (from engine.io changelog):

* [fix] Initialize the WebSocket server in the Server constructor (#476)
* [chore] Bump ws to version 1.1.2 (vulnerability fix) (#480)
2017-02-16 22:01:53 +01:00
Tim Ruffles
5b79ab1af1 [docs] Update the wording to match the code example (#2853) 2017-02-13 23:52:07 +01:00
Damien Arrachequesne
54ff591b07 [feature] Merge Engine.IO and Socket.IO handshake packets (#2833) 2017-02-01 15:28:14 +01:00
H3rby7
e1facd5155 [docs] Small addition to the Express Readme Part (#2846) 2017-02-01 15:23:56 +01:00
Damien Arrachequesne
3b92cc2b26 [feature] Allow the use of custom parsers (#2829) 2017-01-24 07:10:19 +01:00
Damien Arrachequesne
3d695c60f1 [chore] Bump engine.io to version 2.0.0 (#2832) 2017-01-23 23:16:51 +01:00
Antoine LUCAS
3b5f4339a7 [fix] Use path.resolve by default and require.resolve as a fallback (#2797)
Browserify doesn't support require.resolve, and as a consequence, makes nexe fail the compilation. This PR attempts to get the path of the socket.io-client file via path.resolve and falls back to the original require.resolve if this file cannot be found.
2017-01-22 07:21:45 +01:00
Damien Arrachequesne
23c9dd34d5 [docs] Add a 'Features' section in the README (#2824) 2017-01-16 23:16:46 +01:00
Damien Arrachequesne
e28b475428 [docs] Add httpd cluster example (#2819) 2017-01-16 08:33:22 +01:00
Damien Arrachequesne
f7eed6e397 [docs] Add haproxy cluster example (#2818) 2017-01-16 08:33:09 +01:00
Damien Arrachequesne
988852986a [docs] Add nginx cluster example (#2817) 2017-01-16 08:32:53 +01:00
Damien Arrachequesne
8eaba085de [docs] Implement whiteboard example (#2810) 2017-01-16 08:32:33 +01:00
Tom Atkinson
2258a6a6e3 [fix] Properly close the connection on error (#2681) 2017-01-16 08:29:11 +01:00
Tom Atkinson
ad658b8cc2 [perf] Use shared instance of the encoder (#2825) 2017-01-16 08:25:52 +01:00
Tom Atkinson
e24434a0a0 [perf] Reset properties instead of deleting them (#2826)
Deleting properties is a v8 'optimization killer'
2017-01-16 08:23:22 +01:00
Damien Arrachequesne
b754cff2b4 [docs] Fix documentation for local flag (#2816) 2017-01-10 18:10:56 +01:00
Damien Arrachequesne
706ca2a0c1 [docs] Add emit cheatsheet (#2815) 2017-01-10 17:54:09 +01:00
Damien Arrachequesne
accd0bd64a [docs] Add pingInterval/pingTimeout/transports options in the API documentation (#2814) 2017-01-10 17:50:38 +01:00
Damien Arrachequesne
131a2befec [docs] Add an example for socket.join() method (#2813) 2017-01-10 17:46:54 +01:00
Damien Arrachequesne
0be865f614 [docs] Fix a typo on clients method in the API documentation (#2812) 2017-01-10 17:41:31 +01:00
Damien Arrachequesne
01b262fbe0 [chore] Update issue template with fiddle (#2811) 2017-01-10 10:16:27 +01:00
Bella
f260439933 [chore] Update copyright year LICENSE to 2017 (#2803) 2017-01-06 17:11:03 +01:00
Andrea Accardo
e04de3c2c8 [docs] Fix wrong argument name in API.md (#2802) 2017-01-04 06:37:12 +01:00
Ian Bro
a27802e19e [fix] Prevent null from being accepted as argument (#2606) 2016-12-30 16:22:16 +01:00
Gatsbill
c46d4481bd [perf] micro-optimisations (#2793) 2016-12-30 16:18:09 +01:00
bananaapple
d82190016f [docs] Add install script on Readme.md (#2780) 2016-12-30 16:11:26 +01:00
Damien Arrachequesne
255b845596 [docs] API documentation (#2784) 2016-12-30 16:10:54 +01:00
Damien Arrachequesne
1f59e4526a [chore] Release 1.7.2 (#2783) 2016-12-11 02:04:21 +01:00
Damien Arrachequesne
0a7afa85ea [chore] Bump engine.io to version 1.8.2 (#2782) 2016-12-11 01:27:19 +01:00
Serhii Sol
1e31769062 [fix] Fixes socket.use error packet (#2772)
* fix(socket): Fixes socket.use error packet which drops nodejs due to nuances of Nodejs' EventEmitter

* fix(socket): Fixes missing error event on socket

* fix(socket): test fix, should listen for clientSocket instead of server socket

* minor update
2016-12-01 02:25:13 +01:00
Damien Arrachequesne
797c9a3498 [chore] Release 1.7.1 (#2768) 2016-11-28 00:06:18 +01:00
Damien Arrachequesne
4f93a0b429 [chore] Release 1.7.0 (#2767) 2016-11-27 08:27:39 +01:00
Damien Arrachequesne
3c98130f15 [chore] Update client location and serve minified file (#2766)
Following https://github.com/socketio/socket.io-client/pull/1025, the
output files are now generated in the dist directory.
2016-11-27 08:24:27 +01:00
Damien Arrachequesne
9c23308c6e [chore] Bump engine.io to version 1.8.1 (#2765) 2016-11-27 07:55:02 +01:00
Tal Beja
955e5e0d91 [feature] Add a local flag (#2628)
That new flag will prevent the adapter (redis) from publishing the emit to the pub/sub server.

When several instances of a server receive the same event from a third party (not from a client), each server instance broadcasts the event to all his clients. With the local flag, and the change in the redis adapter, each server instance send the event only to his client, so each client receive only one unique event.
2016-11-24 23:44:52 +01:00
Zhu Liang
0ef55b26d4 [feature] serve sourcemap for socket.io-client (#2482) 2016-11-24 23:39:43 +01:00
Robbie Ferguson
4d8e2d342c [docs] Fixed grammar issues in the README.md (#2159)
Added a few periods and commas which were missing. Pluralised the word
'parameter' where it was incorrectly specified to singular on line 281.
Very minor edit. No source code changed.
2016-11-23 15:05:15 +01:00
Jérémy Lal
d48f848bb4 [docs] Comment connected socket availability for adapters (#2081) 2016-11-23 15:00:07 +01:00
Damien Arrachequesne
57b386385e [chore] Release 1.6.0 (#2757) 2016-11-20 04:26:56 +01:00
Damien Arrachequesne
9e7567daee [chore] Bump socket.io-adapter to version 0.5.0 (#2756) 2016-11-20 03:51:57 +01:00
Damien Arrachequesne
2e36799b17 [chore] Bump engine.io to version 1.8.0 (#2755) 2016-11-20 03:50:32 +01:00
Damien Arrachequesne
9bb5e9de2f [chore] Bump debug to version 2.3.3 (#2754) 2016-11-20 03:42:09 +01:00
Luca Tabone
ff2c15de68 [perf] Minor code optimizations (#2219) 2016-11-18 02:03:06 +01:00
Damien Arrachequesne
a483658607 [example] Add disconnection/reconnection logs to the chat example (#2675) 2016-11-18 01:52:45 +01:00
Julian Grinblat
4c5dbd8824 [fix] Don't drop query variables on handshake (#2745)
Parameters passed during handshake, such as tokens, were being dropped.
2016-11-16 01:17:19 +01:00
mhmeadows63
e14a10b7ce [feature] add support for Server#close(callback) (#2748) 2016-11-15 21:52:56 +01:00
Alex
5a123beea5 [feature] Add support for socket middleware (#2306) 2016-11-05 01:51:29 +01:00
Philip YoonShin
2ed5f0f5fb [chore] Update year to 2016 (#2456) 2016-11-05 01:19:15 +01:00
Julian Grinblat
e9f980c475 [feature] Add support for all event emitter methods (#2601) 2016-11-05 01:14:21 +01:00
Jamie Davis
6f44f3a8ef [test] Fix leaking clientSocket (#2721)
Test 'should be able to close sio sending a port' defined a clientSocket
but didn't set 'reconnection: false'.

Now, the default behavior of a clientSocket is 'reconnection: true'.
As a result, the clientSocket was "leaked" from the test case
and seemed to intermittently connect to the servers in subsequent
test cases. This would cause other tests to timeout unexpectedly.

It's not clear to me why this would happen, since the test case
assigns a unique port number to the socket.
However, if you go into socket.io-client and assign and log
unique IDs to each socket, then you'll see that this clientSocket
shows up in other test cases if the reconnectionDelay strikes
unluckily.
2016-11-05 01:06:04 +01:00
Atanas Palavrov
04fc0f3677 [feature] Loading client script on demand. (#2567)
Support for the serving of the client script mess with packagers like
browserify, webpack. Especcialy in projects where it is not used at all.
This patch is workaround to avoid that problem in the cases when client
script is not served.
2016-10-30 14:22:00 +01:00
Kenton Varda
d026c00d05 [fix] Make ETag header comply with standard. (#2603)
The standard says that an ETag must be surrounded in double quotes:

https://tools.ietf.org/html/rfc7232#section-2.3

Although browsers tend to be lenient, omitting the quotes can confuse/break some kinds of proxies and other tools that demand compliant formatting. For example, Sandstorm.io enforces strict HTTP usage for security reasons and will block responses with invalid ETags.
2016-10-30 14:19:00 +01:00
Damien Arrachequesne
fdf64cc38f [chore] Release 1.5.1 (#2735) 2016-10-24 03:31:32 +02:00
Damien Arrachequesne
5badb6436e [chore] Bump socket.io-parser to 2.3.1 (#2734) 2016-10-24 03:23:03 +02:00
Damien Arrachequesne
c20e0b26c9 [chore] Bump engine.io to 1.7.2 (#2729) 2016-10-24 03:21:11 +02:00
bananaapple
5c10c5439b [test] Use client function to unify client in test script (#2731) 2016-10-24 02:35:01 +02:00
Damien Arrachequesne
8182ecc61c [chore] Add Github issue and PR templates (#2733) 2016-10-22 09:19:08 +02:00
Feram Bot
ccd3376627 [docs] Minor fixes (#2526) 2016-10-21 03:21:45 +02:00
Damien Arrachequesne
58a73d39e9 [chore] Bump socket.io-parser to 2.3.0 (#2730) 2016-10-21 03:18:49 +02:00
Tom Atkinson
e60bd5a4da [fix] Avoid swallowing exceptions thrown by user event handlers (#2682) 2016-10-21 03:16:36 +02:00
Paul Meinhardt
21dffa4b58 [docs] Link readme npm package badge to npm registry page (#2612) 2016-10-21 03:10:33 +02:00
Marcio Puga
94852e3d23 [docs] Fix typo (#2724) 2016-10-21 03:06:59 +02:00
davidlondono
b8c60506a6 [docs] Fix JSDoc of optional parameters (#2465)
Making proper optional Docs for socketIO
2016-10-21 03:02:59 +02:00
syuilo⭐️
ecc76f48bc [docs] Add link to LICENSE (#2221) 2016-10-21 03:00:38 +02:00
Damien Arrachequesne
c94058f9b0 [chore] release 1.5.0 (#2711) 2016-10-07 00:13:33 +02:00
Damien Arrachequesne
43d9a4b55d [feature] Add a 'disconnecting' event to access to socket.rooms upon disconnection (#2332) 2016-10-06 23:23:26 +02:00
Alejandro Oviedo
df916172dd [chore] Link build badge to master branch (#2549) 2016-10-06 23:12:15 +02:00
Damien Arrachequesne
271c625243 [chore] Restrict files included in npm package (#2709) 2016-10-06 23:11:33 +02:00
Damien Arrachequesne
628fe8f1b2 [chore] Point towards current master of socket.io-client (#2710) 2016-10-06 23:10:54 +02:00
Damien Arrachequesne
db62e1bf67 [chore] Remove unused zuul-ngrok dependency (#2708) 2016-10-06 23:10:33 +02:00
YasharF
ba4c7921ef [chore] Bump engine.io to 1.7.0 (#2707) 2016-10-06 10:03:55 +02:00
Damien Arrachequesne
30ea0b8d7d Merge pull request #2599 from boazsegev/patch-1
Documentation update to help new programmers
2016-08-05 21:07:30 +02:00
Bo
2d141aff7c Prevent mixup for new programmers
The documentation, inadvertently, causes confusion for newer programmers, hindering their learning curve and ability to learn `socket.io` faster.

This proposed change aims at preventing this confusion to allow new programmers easier access to resources, especially when searching the web for more information.

The name `socket` in the documentation refers to the API gateway, or abstraction layer, related to the `client` and other properties. However, in the rest of the programming world, `sockets` usually refer to Berklee sockets or the lower-level communication channel that is used to implement Protocols such as the Websocket Protocol and HTTP.

New programmers often search for more informations using the `sockets` keyword when they are grappling with learning the `socket.io` API.

A good example is the stack overflow site, where newer programmers incorrectly tag their questions `sockets` and in turn don't get a fast response to their questions.

By simply changing the name of the variable used to describe socket.io's "Socket" class instances from `socket` to `client`, this mixup should be mitigated considerably.
2016-06-26 14:32:37 -04:00
Guillermo Rauch
40763d3962 1.4.8 2016-06-23 19:24:38 -07:00
Guillermo Rauch
2a092bd2fb Release 1.4.8 2016-06-23 19:22:41 -07:00
Guillermo Rauch
4137eb5c43 package: bump engine.io 2016-06-23 19:12:28 -07:00
Guillermo Rauch
e3207005da 1.4.7 2016-06-23 17:31:33 -07:00
Guillermo Rauch
42aa77614e Release 1.4.7 2016-06-23 17:25:46 -07:00
Guillermo Rauch
1491a96c95 package: bump engine.io 2016-06-23 17:11:15 -07:00
Guillermo Rauch
dcca01f5a4 Release 1.4.6 2016-05-02 20:57:44 -07:00
Guillermo Rauch
3b58fa04d5 package: bump engine.io 2016-05-02 20:56:15 -07:00
Naoyuki Kanezawa
0c6d50d9c0 Merge pull request #2416 from nus-fboa2016-si/chatexample
updated express version to express 4
2016-04-12 03:58:08 +09:00
Naoyuki Kanezawa
881f16553c Merge pull request #2508 from tw0517tw/quote-exec
add quote to exec paths, prevent error when spaces in path
2016-04-12 03:57:43 +09:00
Guillermo Rauch
e5a8d4d2d9 Merge pull request #2520 from nkzawa/fix/ignore-dist
Ignore dist directory for now
2016-04-11 08:45:11 -07:00
Guillermo Rauch
fb0253edea Merge pull request #2422 from nus-fboa2016-si/queryStringFix
Fix for Issue #331 on socket.io-client
2016-04-11 08:44:59 -07:00
tw0517tw
3c5f5a0864 use a bigger timeout for slower machine 2016-04-11 22:31:47 +08:00
tw0517tw
a23d26a617 add quote to exec paths, prevent error when spaces in path 2016-04-11 22:21:34 +08:00
Zhu Liang
910b5d77a6 fixed version notation 2016-04-11 22:19:49 +08:00
Naoyuki Kanezawa
438ad63cdf Merge pull request #2420 from revington/test-node-v5-stable
[Travis] Add Node 5.x (Stable) to the test matrix
2016-04-11 23:09:41 +09:00
Naoyuki Kanezawa
7e9a67d8ee Merge pull request #2415 from nus-fboa2016-si/documentation
Documentation
2016-04-11 23:05:33 +09:00
Naoyuki Kanezawa
0ae070885d Merge pull request #2477 from callahad/chat-layout-fix
Fix chat display in Firefox
2016-04-11 23:00:07 +09:00
Naoyuki Kanezawa
36d99d8d84 Merge pull request #2492 from westy92/master
Update package.json
2016-04-11 22:20:46 +09:00
nkzawa
0e63b0910e ignore dist for now 2016-04-11 22:11:19 +09:00
Guillermo Rauch
3c7350fa58 Merge pull request #2509 from tw0517tw/patch-1
stop prepend /# before id when no namespace
2016-04-10 11:24:42 -07:00
Guillermo Rauch
aadd5da655 Merge pull request #2496 from nus-fboa2016-si/compat-test
Added test for compat version transformed by babel
2016-04-02 18:31:30 -07:00
吳東曄 Wu, Dung-Ie
6d4128750b stop append /# before id when no namespace 2016-04-02 01:55:53 +08:00
Zhu Liang
6edcd1c6ba styling fixes 2016-03-31 12:55:42 +08:00
Zhu Liang
6b2394e612 disable loading lib by default to avoid syntax error due to lib containing new es6 syntax 2016-03-31 03:54:32 +08:00
Zhu Liang
677af3fa11 changed env var name, added testing documentation to readme 2016-03-21 13:11:03 +08:00
Zhu Liang
a1ff739b36 babel transpile before test, print error 2016-03-19 20:19:08 +08:00
Zhu Liang
de5b588e17 explicit distinction between current and compat in test so we can serve either compat or current as default 2016-03-19 20:13:57 +08:00
Zhu Liang
5a20c1195b set env vars in travis 2016-03-19 19:49:41 +08:00
Zhu Liang
5253bc400b use multiple npm scripts 2016-03-19 19:41:14 +08:00
Zhu Liang
1245a5639e added compat test 2016-03-19 19:21:54 +08:00
Zhu Liang
88161539a1 implement compat test using env variable 2016-03-17 13:42:29 +08:00
Zhu Liang
d99d4d15ae add compat test for babel-transformed codes 2016-03-17 13:11:20 +08:00
Seth Westphal
06ecfe5444 Explicit local gulp is unnecesary 2016-03-16 13:01:49 -05:00
Seth Westphal
e90b4eba1e Update repository URL 2016-03-16 12:58:59 -05:00
Guillermo Rauch
c7de1a1adf Merge pull request #2471 from nus-fboa2016-si/gulp-rebased
Add gulp and babel
2016-03-12 20:04:48 -08:00
Dan Callahan
7bae6ac636 Fix chat display in Firefox 2016-03-08 19:50:55 -06:00
Diga Widyaprana
355b5156fe Remove node 0.8 from travis 2016-03-09 09:36:51 +08:00
Diga Widyaprana
3e168ee0b8 Redirect make tasks to gulp 2016-03-06 11:40:57 +08:00
Diga Widyaprana
ed9ab77dcb Minor fixes to gulp tasks
- Only provide entry point as first argument of gulp.src
- {read:false} option for mocha tests
- change timeout:2000 to slow:200 to mirror makefile's mocha options
- replace var with const where appropriate
2016-03-06 11:40:57 +08:00
Diga Widyaprana
1104cd135e Use local instead of global gulp in npm test 2016-03-06 11:40:57 +08:00
Diga Widyaprana
0be915cd0f Add gulp task clean to clean transpile output
- Work done by @YijinL. Part of @05ad308
2016-03-06 11:40:57 +08:00
Diga Widyaprana
c6dd41b915 Minor refactoring to transpile task
- Transpiling is now gulp transpile
- Default redirects to transpile
- Refactor transpile output directory to a separate constant
- Work by @YijinL in @05ad308
2016-03-06 11:32:40 +08:00
Diga Widyaprana
0f14312d7b Add gulp help
Work was done by @YijinL in 2 separate commits (@9204125 and @05ad308)
2016-03-06 11:32:09 +08:00
Diga Widyaprana
97bd95f036 Don't use dynamic dependencies 2016-03-04 18:06:00 +08:00
Diga Widyaprana
11e0f19272 Inline babel configuration 2016-03-04 18:06:00 +08:00
Yijin
e388a3319d npm test script to use gulp 2016-03-04 18:06:00 +08:00
Zheng Weihan
b551ce9835 added test-cov task. 2016-03-04 18:06:00 +08:00
Zhu Liang
0bac96a6b2 added comment for babel 2016-03-04 14:46:08 +08:00
Zhu Liang
1d07b10339 integrated babel into gulp 2016-03-04 14:46:08 +08:00
Zheng Weihan
398b5479f0 delete unused dependency 2016-03-04 14:45:55 +08:00
Zheng Weihan
d9eb729eab implement gulp build system for test. 2016-03-04 14:45:03 +08:00
whattokingu
f9db72997f Merge pull request #10 from whattokingu/queryStringFix
Query string fix
2016-02-14 13:57:06 +08:00
Zheng Weihan
1293505dc2 update tests. 2016-02-14 13:48:28 +08:00
Zheng Weihan
f4e9e71c56 Merge branch 'queryStringFix' of https://github.com/whattokingu/socket.io into queryStringFix
# By whattokingu
# Via whattokingu
* 'queryStringFix' of https://github.com/whattokingu/socket.io:
  conform to style guide

Conflicts:
	lib/client.js
2016-02-14 13:47:59 +08:00
Zheng Weihan
045674de97 remove unnecessary decoder. url.parse already decodes string.
add test to test decoding function.
2016-02-14 13:46:26 +08:00
whattokingu
7091acf24c Merge pull request #9 from whattokingu/queryStringFix
Query string fix
2016-02-13 14:41:15 +08:00
whattokingu
19341051e8 conform to style guide 2016-02-13 14:35:12 +08:00
Zheng Weihan
e141e09aaf change decodeUriComponents calls 2016-02-13 14:28:21 +08:00
Zheng Weihan
5fabe4e780 call decodeURIComponent on query received from client.
update package.son to point to latest commit in socket.o-client package (with URI encoder)
2016-02-13 14:10:20 +08:00
whattokingu
7760a71d90 Merge pull request #8 from whattokingu/queryStringFix
add comments to code
2016-02-04 13:28:29 +08:00
Zheng Weihan
c077357eff add comments to code 2016-02-04 13:27:36 +08:00
whattokingu
2f26a2bdb4 Merge pull request #7 from whattokingu/queryStringFix
add test for issue #331 on socket.io-client.
2016-01-31 15:45:35 +08:00
Zheng Weihan
13af610f6d add test for issue #331 on socket.io-client. 2016-01-31 15:44:39 +08:00
whattokingu
abcedf53ec Merge pull request #6 from whattokingu/queryStringFix
sync to master branch
2016-01-31 11:23:02 +08:00
Zheng Weihan
24456fdcbe Merge branch 'master' into queryStringFix
* master:
  Release 1.4.5
  package: bump `engine.io`
  add a test for graceful shutdown
2016-01-31 11:21:30 +08:00
Pedro Narciso García Revington
25116ab179 test node 5 (stable) 2016-01-30 21:53:04 +01:00
Zhu Liang
a116d52e30 updated express version to express 4 2016-01-30 11:57:31 +08:00
whattokingu
cecf5f127e Merge pull request #5 from whattokingu/documentation
Added Documentation
2016-01-30 11:31:11 +08:00
Zheng Weihan
1c467e15e6 Issue #2400, added documentation 2016-01-30 11:28:40 +08:00
whattokingu
a110542563 Merge pull request #4 from whattokingu/queryStringFix
Fix for Issue #331 on socket.io-client
2016-01-30 10:16:19 +08:00
Zheng Weihan
7d55724468 refactor parsing of URL in CONNECT packet to use 'url' library. 2016-01-30 09:47:28 +08:00
Zheng Weihan
1d84c55743 fix to issue #331 on socket.o-client.
Parses CONNECT packet for query string and replaces query in socket.handshake.
2016-01-28 14:40:05 +08:00
Guillermo Rauch
b3fc530abe Release 1.4.5 2016-01-26 13:26:17 -08:00
Guillermo Rauch
d0dfa54dcb package: bump engine.io 2016-01-26 10:42:41 -08:00
Guillermo Rauch
198b836759 Merge pull request #2399 from nkzawa/graceful-close
Add a test for graceful shutdown
2016-01-21 09:15:36 -08:00
nkzawa
a75f46f06f add a test for graceful shutdown 2016-01-21 20:50:44 +09:00
Naoyuki Kanezawa
2a91fd57c7 Merge pull request #2344 from denghongcai/patch-2
fix wrong jsdoc
2016-01-17 15:25:32 +09:00
Naoyuki Kanezawa
fe891293b2 Merge pull request #2353 from faizalpribadi/patch-1
fix typo word :)
2016-01-17 15:23:35 +09:00
Naoyuki Kanezawa
6e450f75b4 Merge pull request #2374 from darrachequesne/patch-4
Add badges showing dependency status
2016-01-17 15:22:52 +09:00
Naoyuki Kanezawa
22c985cae6 Merge pull request #2380 from darrachequesne/patch-5
Document type change of Socket#rooms
2016-01-17 15:22:05 +09:00
Guillermo Rauch
fea3d79a2c Release 1.4.4 2016-01-10 22:36:31 -08:00
Guillermo Rauch
d3dde130b7 package: bump engine.io 2016-01-10 22:27:44 -08:00
Damien Arrachequesne
899de7f873 Document type change of Socket#rooms 2016-01-09 22:08:30 +01:00
Guillermo Rauch
f1a3e8db2a Release 1.4.3 2016-01-08 08:17:50 -08:00
Guillermo Rauch
dad82c3343 Release 1.4.2 2016-01-07 18:58:05 -08:00
Guillermo Rauch
a6cbf6b205 package: bump engine.io 2016-01-07 18:14:39 -08:00
Damien Arrachequesne
580100d491 Bump dev dependencies 2016-01-07 22:59:28 +01:00
Damien Arrachequesne
acb9cb421d Add badges showing dependency status 2016-01-07 22:58:59 +01:00
Guillermo Rauch
6d5d7e4411 Release 1.4.1 2016-01-07 12:52:27 -08:00
Guillermo Rauch
ddb3445f3d Release 1.4.0 2016-01-05 15:44:48 -08:00
Guillermo Rauch
6eb9807f17 package: bump engine.io for sec advisory 2016-01-05 13:40:54 -08:00
Faizal Pribadi
abe2394a24 fix typo word :)
update docs source code
2015-12-20 16:16:42 +07:00
Hongcai Deng
7012ba6c64 fix wrong jsdoc 2015-12-14 15:31:42 +08:00
Guillermo Rauch
7b0073c00f Merge pull request #2335 from nkzawa/patch-7
Improve the chat demo
2015-12-04 17:10:23 -08:00
nkzawa
0313ad0ea3 improve the chat demo 2015-12-05 10:07:08 +09:00
Guillermo Rauch
d310d42472 package: bump engine.io 2015-12-04 10:56:08 -08:00
Guillermo Rauch
709ceba00a package: bump socket.io-adapter for release 2015-12-03 10:28:33 -08:00
Guillermo Rauch
b29312bc61 package: bump engine.io for node 0.8 fix 2015-12-01 12:15:36 -08:00
Guillermo Rauch
51901160df package: temporarily revert version for tests 2015-12-01 11:24:06 -08:00
Guillermo Rauch
ab1b36e13f package: bump engine.io for ws memory fix 2015-11-30 08:16:21 -08:00
Guillermo Rauch
f7a2f35590 package: bump engine.io 2015-11-28 16:34:44 -08:00
Guillermo Rauch
c348737fe6 socket.io: increase large binary data test timeout 2015-11-28 15:13:13 -08:00
Guillermo Rauch
dde3737165 package: bump engine.io for release 2015-11-28 12:07:08 -08:00
Guillermo Rauch
8df4c7931b Merge pull request #2325 from darrachequesne/patch-2
Trigger callback even when joining an already joined room
2015-11-28 10:56:46 -08:00
Damien Arrachequesne
1dfacc6647 Trigger callback even when joining an already joined room 2015-11-27 22:08:18 +01:00
Guillermo Rauch
35a0fe0377 package: bump parser 2015-11-25 10:14:56 -08:00
Guillermo Rauch
3b00312fa7 namespace: clear rooms flag after a clients call (fixes #1978) 2015-11-23 09:40:57 -08:00
Guillermo Rauch
7b420295ef Merge pull request #2249 from pmq20/minqi-another
[Travis] Add Node 4.x to the test matrix
2015-11-23 09:31:48 -08:00
Guillermo Rauch
c504315982 Merge pull request #2322 from darrachequesne/issue-2199-clean
Add hasOwnProperty checks
2015-11-23 09:19:35 -08:00
Guillermo Rauch
520b5c37d5 Merge pull request #2321 from nkzawa/patch-6
Update redirects in README
2015-11-23 09:19:03 -08:00
Damien Arrachequesne
09f446eca0 Add hasOwnProperty checks 2015-11-23 15:12:21 +01:00
Naoyuki Kanezawa
aecf3bf71c Merge pull request #2218 from futbalguy/master
Clarified documentation of Socket.in
2015-11-23 17:37:07 +09:00
nkzawa
6c0a79e2b9 update redirects in README 2015-11-23 17:28:11 +09:00
Guillermo Rauch
8683206e31 Merge pull request #2239 from darrachequesne/issue-2199
converted arrays to objects
2015-11-22 10:34:57 -08:00
Guillermo Rauch
988d9d2346 Merge pull request #1999 from nkzawa/patch-3
Fix a few assertions are not executed properly
2015-11-22 10:17:02 -08:00
Damien Arrachequesne
b73d9bea4e converted arrays to objects 2015-11-22 11:12:40 +01:00
Naoyuki Kanezawa
d4fb6a5904 Merge pull request #2316 from tripu/master
Update “debug” to avoid vulnerability in “ms”
2015-11-22 10:39:23 +09:00
tripu
0517c609ba Avoid ^ in "debug" dependency (fixes #2314) 2015-11-21 23:59:16 +01:00
tripu
aa9438fee2 Update package "debug" to avoid "ms" vulnerability 2015-11-21 23:55:00 +01:00
Guillermo Rauch
aee466cc71 Update Readme.md 2015-11-21 10:54:19 -08:00
Guillermo Rauch
65f75d7732 Merge branch 'master' of github.com:socketio/socket.io 2015-11-21 10:46:26 -08:00
Guillermo Rauch
279c52a4c5 package: bump socket.io-parser 2015-11-21 10:45:43 -08:00
Naoyuki Kanezawa
67d1a67b1c Merge pull request #2319 from darrachequesne/patch-3
Minor fix
2015-11-21 23:21:39 +09:00
Damien Arrachequesne
aae68d74b1 Minor performance optimization 2015-11-20 22:03:03 +01:00
Damien Arrachequesne
bf5897cedc Fixed tests with large data 2015-11-20 22:01:16 +01:00
Damien Arrachequesne
a1a1c6657a Removed unused variable 2015-11-20 22:00:42 +01:00
Guillermo Rauch
2a4f7ae161 Merge pull request #2136 from nkzawa/patch-5
Don't set request property
2015-11-20 12:59:05 -08:00
Naoyuki Kanezawa
dba0576ca9 Merge pull request #2317 from ChaofengZhou/master
fixed a typo in the example code
2015-11-20 13:13:10 +09:00
Chaofeng
ba90f0991b fixed a typo in the example code 2015-11-19 21:09:34 -07:00
Guillermo Rauch
9a54e9cace package: bump mocha 2015-11-18 19:53:25 -08:00
Guillermo Rauch
9df4cb64b8 bump zuul-ngrok 2015-11-18 19:51:47 -08:00
Guillermo Rauch
c8f525868a package: bump has-binary 2015-11-18 16:56:06 -08:00
Guillermo Rauch
a39d7c2ae4 Merge pull request #2171 from KevinMartin/patch-1
Actually prevent double callbacks...
2015-11-18 12:56:01 -08:00
Guillermo Rauch
4ba266d404 Merge pull request #2307 from darrachequesne/patch-1
Upgrade npm version in order to fix node v0.8 build
2015-11-16 15:55:20 -08:00
Damien Arrachequesne
6b49779420 Upgrade npm version in order to fix node v0.8 build 2015-11-17 00:44:42 +01:00
Guillermo Rauch
b1775b1cb8 Merge pull request #2051 from tobalsgithub/master
Allowing a custom function for opts.allowRequest
2015-11-16 13:15:08 -08:00
Guillermo Rauch
ef52967301 Merge pull request #2271 from dazorni/master
Working travis build status
2015-11-16 13:12:26 -08:00
Guillermo Rauch
fde38b1bd7 Merge pull request #2208 from odeke-em/fix-legacy-repo-info
README: fixed up legacy repo links
2015-11-16 13:10:24 -08:00
Sebastian Zorn
75da57abb2 Working travis build status 2015-10-06 21:42:33 +02:00
Guillermo Rauch
21ea31a34e Merge branch '1.3.7-patch' 2015-09-21 04:30:59 +04:00
Guillermo Rauch
e2ebd4349b Release 1.3.7 2015-09-21 04:21:11 +04:00
Guillermo Rauch
b771f74a22 package: bump socket.io-client for node4 compatibility 2015-09-21 04:16:59 +04:00
Guillermo Rauch
8744007dc7 package: bump engine.io for node4 compatibility 2015-09-21 04:10:19 +04:00
P.S.V.R
3658928ee7 [Travis] Add Node 4.x to the test matrix 2015-09-16 17:39:26 +08:00
Guillermo Rauch
210e688732 package: bump engine.io 2015-09-09 15:47:14 -07:00
Guillermo Rauch
ae5420b727 package: bump engine.io and socket.io-client 2015-08-30 10:51:25 -07:00
futbalguy
d5b3bb46f8 Clarified documentation of Socket.in 2015-08-23 10:12:23 -07:00
Emmanuel Odeke
575d35a371 README: fixed up legacy repo links 2015-08-16 20:36:39 -06:00
Guillermo Rauch
e41483be9e Merge branch '1.3.6-patch' 2015-07-14 20:04:44 -07:00
Guillermo Rauch
c79e787671 test: better timeout for stress test 2015-07-14 19:58:42 -07:00
Guillermo Rauch
a2f6bb99d6 Merge branch '1.3.6-patch' 2015-07-14 18:02:56 -07:00
Guillermo Rauch
3e4061bfef Release 1.3.6 2015-07-14 17:59:50 -07:00
Guillermo Rauch
4c1d691fe5 package: bump engine.io to fix build on windows 2015-07-09 09:28:43 -07:00
Kevin Jose Martin
514aeb4fcd Actually prevent double callbacks...
We declare `sent = false` and even check `if (sent)` is truthy, but we never set it to truthy, therefore it never really *prevents double callbacks*...
2015-07-06 11:36:00 -04:00
Nathan Rajlich
876833198d Merge pull request #2111 from kemitchell/spdx-license
Use a Standard-Compliant License Identifier
2015-06-05 11:51:30 -07:00
Naoyuki Kanezawa
4d36d6c01a don't set request property 2015-05-30 03:34:05 +09:00
Guillermo Rauch
43fa075ec4 bump client 2015-05-27 22:56:15 -07:00
Guillermo Rauch
91c7bde34b Merge commit '342faf219793fc5c1f130fc33e3fb5422dab516d' 2015-05-27 22:55:15 -07:00
Guillermo Rauch
874a4a8535 package: bump client 2015-05-27 08:19:15 -07:00
Guillermo Rauch
93b571406e package: bump engine.io to fix build issues 2015-05-25 14:34:10 -07:00
Kyle Mitchell
98af793f07 use a valid SPDX license identifier 2015-05-05 00:08:44 +00:00
Guillermo Rauch
3f72dd3322 Merge pull request #2063 from kapouer/patch-1
Let adapter.add find connected socket
2015-04-10 21:38:41 -07:00
Guillermo Rauch
d0d38220fb Update Readme.md 2015-04-08 16:53:04 -07:00
Guillermo Rauch
f8aa157d5d remove proxy index file 2015-04-05 16:53:28 -07:00
Guillermo Rauch
0e13e9a268 bumped adapter 2015-04-05 15:52:59 -07:00
Guillermo Rauch
916872587f Merge pull request #2013 from nkzawa/namespace-flags
Supports flags on namespace
2015-04-05 15:51:54 -07:00
Guillermo Rauch
a7072845ea Merge pull request #2006 from nkzawa/patch-4
improve Socket#packet and Client#packet and enable volatile and compress when broadcast
2015-04-05 15:51:49 -07:00
Jérémy Lal
425409945b Let adapter.add find connected socket
When a socket connects, it joins its own room, resulting in a call to adapter.add.
The adapter in turn should be able to find the socket by id.
2015-03-24 14:54:52 +01:00
Guillermo Rauch
5826ef0bb5 Merge pull request #2059 from rase-/update/debug
Bump debug to 2.1.3
2015-03-17 16:42:00 -07:00
Tony Kovanen
14e32a9bad Bump debug to 2.1.3 2015-03-18 01:40:19 +02:00
TC
1dde0f3947 Allowing a custom function for opts.allowRequest 2015-03-12 15:50:31 -06:00
Guillermo Rauch
342faf2197 Release 1.3.5 2015-03-03 10:50:10 -08:00
Guillermo Rauch
12c6ee132d improve test 2015-03-03 10:34:56 -08:00
Guillermo Rauch
c9d909c993 package: bump socket.io-parser 2015-03-03 10:34:40 -08:00
Guillermo Rauch
125ab51338 test: added test for parser breakage 2015-03-03 10:08:26 -08:00
Guillermo Rauch
b31ac18554 test with 0.12 2015-02-19 15:38:35 -08:00
Naoyuki Kanezawa
53cdd8f1fc support flags on namespace 2015-02-20 03:34:09 +09:00
Naoyuki Kanezawa
81aea995ed improve Socket#packet and Client#packet 2015-02-15 04:33:20 +09:00
Guillermo Rauch
1b2d902f33 Release 1.3.4 2015-02-14 10:57:50 -08:00
Guillermo Rauch
9536437907 package: bump socket.io-client 2015-02-14 10:55:15 -08:00
Naoyuki Kanezawa
56fe26661d fix a few assertions 2015-02-12 06:09:30 +09:00
Guillermo Rauch
29974ac777 Release 1.3.3 2015-02-03 17:27:51 -08:00
Guillermo Rauch
ef23c74bea remove compression tests 2015-02-03 17:07:43 -08:00
Guillermo Rauch
49423d70bc added failing tests 2015-02-03 17:04:33 -08:00
Guillermo Rauch
715c7f99b4 socket: warn node_redis-style about missing error 2015-02-03 17:04:06 -08:00
Guillermo Rauch
f2ea965c6b package: bump parser 2015-02-03 16:32:48 -08:00
Guillermo Rauch
a93d05a9f3 package: bump parser 2015-02-03 16:30:49 -08:00
Guillermo Rauch
5ce06d3088 socket: warn node_redis-style about missing error 2015-02-03 16:26:21 -08:00
Guillermo Rauch
816bfec783 added failing tests 2015-02-03 16:26:08 -08:00
Guillermo Rauch
0a17c90d7a test: added failing test 2015-02-03 15:10:46 -08:00
Guillermo Rauch
3645741b86 test: increase timeout for large binary data test 2015-01-31 09:35:37 -08:00
Guillermo Rauch
f2a7322b5a update deps 2015-01-31 08:46:32 -08:00
Guillermo Rauch
97c6568f65 Merge pull request #1966 from cha0s/clients
Suggestion for implementation of clients API
2015-01-31 08:34:43 -08:00
Ruben Rodriguez II
8814825a35 Suggestion for implementation of clients API 2015-01-31 02:17:49 -06:00
Guillermo Rauch
58eaecad27 Merge branch 'master' of github.com:Automattic/socket.io 2015-01-29 20:39:00 -08:00
Guillermo Rauch
94157e650e point to master 2015-01-29 20:38:36 -08:00
Guillermo Rauch
0935b81da2 Merge pull request #1963 from michael-luo/bugfix/1956
bugfix/1956 test for don't reuse same-namespace connections
2015-01-29 20:34:38 -08:00
Michael Luo
afa871bb8a bugfix/1956 test for don't reuse same-namspace connections 2015-01-24 20:19:16 -08:00
Guillermo Rauch
1b01e16a6c fix broken previous commit 2015-01-24 08:02:05 -08:00
Guillermo Rauch
bd6f638c8f package: bump to work with all objects (fixes #1955) 2015-01-24 07:06:30 -08:00
Guillermo Rauch
83b36e54ac Merge pull request #1958 from nkzawa/compress
Support compression
2015-01-23 10:04:43 -08:00
Guillermo Rauch
2f0d9d05af fix origin verification default https port [evanlucas]
for PR #1693
2015-01-22 21:41:59 +00:00
Naoyuki Kanezawa
429eb0cb7c point to the specific commit 2015-01-22 05:26:37 +09:00
Naoyuki Kanezawa
ac8e8598d7 support compression 2015-01-22 05:01:45 +09:00
Guillermo Rauch
9ba6d47ec7 Release 1.3.2 2015-01-19 15:14:18 +00:00
Guillermo Rauch
3d49cafd03 Release 1.3.1 2015-01-19 11:37:14 +00:00
Guillermo Rauch
77ca2dcbda package: bump engine.io (noop) 2015-01-19 11:11:12 +00:00
Guillermo Rauch
7e4aa4fa64 Release 1.3.0 2015-01-19 10:25:49 +00:00
Guillermo Rauch
b46e480f65 Update Readme.md 2015-01-19 09:26:12 +00:00
Guillermo Rauch
5e92dd8663 package: bump socket.io-client 2015-01-18 19:42:43 +00:00
Guillermo Rauch
f981d3f050 package: bump engine.io 2015-01-18 19:41:45 +00:00
Guillermo Rauch
f57505fee7 Merge branch 'master' of github.com:Automattic/socket.io 2015-01-18 18:53:17 +00:00
Guillermo Rauch
f8f1b132a1 package: bump socket.io-client 2015-01-18 18:52:06 +00:00
Guillermo Rauch
f7f83bc09f package: bump engine.io 2015-01-18 18:51:27 +00:00
Guillermo Rauch
b8ded0d725 Merge pull request #1903 from rase-/add/volatile-tests
Added tests for volatile
2015-01-17 12:23:06 +00:00
Guillermo Rauch
086ccd2708 Merge pull request #1938 from fay-jai/license
update license with up-to-date year range
2015-01-17 12:22:11 +00:00
Guillermo Rauch
864857cb6f Merge pull request #1939 from rase-/add/test-for-emit-after-server-restart
Add test for reconnection after server restarts
2015-01-17 12:21:53 +00:00
Guillermo Rauch
e5a7e422f9 Merge pull request #1943 from eychu/patch-1
Add space in error message
2015-01-17 12:21:38 +00:00
Alexey Chuvashov
f5b75151bd Add space in error message 2015-01-15 01:24:19 +03:00
Tony Kovanen
0523b655da Add test for reconnection after server restarts 2015-01-14 17:22:50 +02:00
Willson Mock
d9415a38e4 update license with up-to-date year range 2015-01-11 00:11:55 -05:00
Roman Shtylman
ca82c09bf2 fix leaving unknown rooms
close #1670
2015-01-10 14:58:50 -08:00
Roman Shtylman
b9aaa1607c Merge pull request #1922 from smart--petea/patch-1
Update Readme.md
2015-01-10 14:48:59 -08:00
Roman Shtylman
d1304c5d82 Merge pull request #1926 from coderaiser/patch-1
package: debug v2.1.0
2015-01-10 14:33:21 -08:00
Guillermo Rauch
bd479a9cd6 Merge pull request #1936 from drewblaisdell/master
Allow null or undefined origins when allowed origins is a function
2015-01-09 16:36:38 -08:00
Drew Blaisdell
a116d7765a Allow null or undefined origins when allowed origins is a function
Requests without an Origin header previously caused an exception to be thrown if the allowed origins passed to the constructor was set to a dynamic function. Omitted origins are now set to an asterisk and passed properly to the origins function.

A test for this case is included in this commit.
2015-01-09 16:30:08 -08:00
Guillermo Rauch
1c6620d564 everything is fixed 2015-01-09 16:25:42 -08:00
Guillermo Rauch
dba462e6da fix tests on 0.11 2015-01-09 16:24:24 -08:00
Guillermo Rauch
19c4422361 package: fix npm test to run on windows 2015-01-09 13:57:45 -08:00
coderaiser
8242dd01ef package: debug v2.1.0 2014-12-26 14:16:27 +02:00
Badarau Petru
17960ed038 Update Readme.md
underylings to underlyings
2014-12-22 07:17:01 +02:00
Tony Kovanen
d9996f0470 Added tests for volatile 2014-12-08 11:19:49 +02:00
Guillermo Rauch
24d06d76dd Release 1.2.1 2014-11-21 04:59:14 +01:00
Guillermo Rauch
4e4bbf918e fix protocol violations and improve error handling (fixes #1880) 2014-11-21 04:16:37 +01:00
Guillermo Rauch
b49f5c82f2 syntax 2014-11-21 04:15:42 +01:00
Guillermo Rauch
5bd67195de Merge branch 'master' of github.com:Automattic/socket.io 2014-11-21 02:57:35 +01:00
Guillermo Rauch
73fe547956 package: bump engine.io for websocket leak fix 2014-11-21 02:56:28 +01:00
Guillermo Rauch
973e6cc982 Merge pull request #1813 from ogwiz2/patch-1
Made comments more consistent
2014-11-12 10:04:09 +01:00
Guillermo Rauch
4a0091b25a Release 1.2.0 2014-10-27 15:54:57 -07:00
Guillermo Rauch
a1bf85b57f package: bump socket.io-parser 2014-10-27 11:52:09 -07:00
Guillermo Rauch
62ad812ee5 package: use latest socket.io-client 2014-10-27 11:51:03 -07:00
Guillermo Rauch
9ae8ed6929 package: bump adapter 2014-10-27 11:46:44 -07:00
Guillermo Rauch
4a11c16cc2 package: bump socket.io-client 2014-10-27 11:09:44 -07:00
Guillermo Rauch
b88a758857 package: bump engine.io 2014-10-27 07:47:51 -07:00
Guillermo Rauch
3352d1d726 Merge branch 'master' of github.com:Automattic/socket.io 2014-10-13 08:52:46 -07:00
Guillermo Rauch
e68557fab6 downloads badge 2014-10-13 08:52:36 -07:00
Alex Jeng
136fe960b7 Made comments more consistent 2014-10-05 22:10:13 -07:00
Tony Kovanen
da358084f0 Merge pull request #1773 from AjayMT/master
Fix usage example for Server#close.
2014-09-26 01:13:18 +03:00
Tony Kovanen
1b4f6a5324 Merge pull request #1777 from akamensky/dynamic-cors
Dynamic cors
2014-09-22 13:38:14 -06:00
Tony Kovanen
99346eddc5 Merge pull request #1788 from jamesanthonyferguson/patch-1
Change grammar issues in the chat/README.md
2014-09-22 12:42:59 -06:00
Tony Kovanen
051ffa0440 Merge pull request #1626 from thanpolas/patch-1
http.Server is a constructor
2014-09-22 12:42:10 -06:00
Tony Kovanen
fa4fa3365a Merge pull request #1690 from rase-/fix/resource-option-bc
Fix resource option BC with the set function
2014-09-22 12:27:35 -06:00
Tony Kovanen
bafa184c6b Merge pull request #1792 from rase-/add/autopruning-test
Add room autopruning test
2014-09-22 12:25:23 -06:00
Tony Kovanen
e3149d5833 Bump adapter version. 2014-09-20 11:12:58 -06:00
Tony Kovanen
ae9d5277a9 Add test to check that empty rooms are autopruned. 2014-09-20 11:12:26 -06:00
James Ferguson
2e440722a6 Change grammar issues in the chat/README.md
Added a few periods and commas which were missing. Also added the word each to clarify how multiple users each enter a unique username.
Very minor edit. No source code changed.
2014-09-18 21:41:28 -07:00
Tony Kovanen
3fe6d4e8ec Merge pull request #1784 from matthewcanty/patch-1
Change "there're" to "there are"
2014-09-17 07:41:46 -06:00
Matthew Canty
3b93c1c562 Change "there're" to "there are"
Not a commonly used contraction and looks a bit odd.
2014-09-17 14:01:01 +01:00
akamensky
e89f82a9b0 Added Server#origins(v:Function) description for dynamic CORS 2014-09-12 11:32:20 +08:00
akamensky
1b90ae2587 Added test coverage for Server#origins(function) for dynamic CORS 2014-09-12 11:13:51 +08:00
akamensky
9658e32e7a Added optional Server#origins(function) for dynamic CORS 2014-09-12 10:53:14 +08:00
Tony Kovanen
99d76664aa Merge pull request #1766 from BrianGeppert/master
package: fix main file for example application 'chat'.
2014-09-11 18:05:58 +03:00
Ajay MT
23eefa527a Fix usage example for Server#close. 2014-09-10 18:11:56 +05:30
Brian Geppert
b49b35b26f package: fix main file for example application 'chat'. 2014-09-04 12:10:43 -05:00
Guillermo Rauch
16483375a7 Release 1.1.0 2014-09-04 12:06:06 +02:00
Guillermo Rauch
ec305bd8df examples: minor fix of escaping 2014-09-04 11:44:02 +02:00
Guillermo Rauch
af07a1c649 package: bump engine.io 2014-09-04 01:57:58 +02:00
Tony Kovanen
5863903d44 Merge pull request #1729 from anupbishnoi/patch-1
Take "" and "/" as equivalent namespaces on server
2014-08-20 11:27:46 +03:00
Anup Bishnoi
f56d4acce6 testing for equivalence of namespaces starting with / or without 2014-08-19 22:19:50 +00:00
Anup Bishnoi
8ea37b7351 Update index.js 2014-08-19 16:17:45 -04:00
Anup Bishnoi
b3cb18d910 Added relevant tests
"" and "/" namespaces are checked for equivalence on server and client
2014-08-18 22:47:06 -04:00
Anup Bishnoi
0e41561d56 Take "" and "/" as equivalent namespaces on server
On server, `.of(name)` should use the same key in `.nsps` object for "" and "/"

Important to use `String(name)` and `===` to keep out keys that don't cast to ""
2014-08-18 22:38:47 -04:00
Guillermo Rauch
83709e9487 Merge pull request #1714 from PeterDaveHello/patch-2
Use svg instead of png to get better image quality
2014-08-12 15:47:12 -07:00
Guillermo Rauch
6f4051aaa7 Merge pull request #1713 from PeterDaveHello/patch-1
make CI build faster
2014-08-12 15:45:58 -07:00
Peter Dave Hello
87bf6910b5 Use svg instead of png to get better image quality 2014-08-12 10:56:04 +08:00
Peter Dave Hello
8946b4ed4c make CI build faster 2014-08-12 10:51:01 +08:00
Guillermo Rauch
a40068b5f3 Merge pull request #1688 from fdellabetta/server_side_namespace
client cannot connect to non-existing namespaces
2014-08-01 13:45:32 +01:00
Guillermo Rauch
9e29ec9b2b Merge pull request #1700 from rase-/fix/rooms
Fix splice arguments and `socket.rooms` value update in `socket.leaveAll`
2014-08-01 13:45:01 +01:00
Tony Kovanen
624e7cb14f Fix splice arguments and socket.rooms value update in socket.leaveAll.
Hat tip @Marreck
2014-08-01 13:20:18 +02:00
Tony Kovanen
b4954d767a Take the instance stored path value into account when attaching to eio if no option specified to attach directly 2014-07-23 19:58:44 +03:00
Filippo Della Betta
f6eb53f5e1 client cannot connect to non-existing namespaces 2014-07-22 13:58:13 +02:00
Guillermo Rauch
9c80317574 Merge pull request #1685 from rase-/fix/remote-address-in-handshake-obj
Fix remote address in handshake obj
2014-07-18 19:47:26 -07:00
Tony Kovanen
d163d891ef Bump engine.io version to get the cached IP address 2014-07-19 04:49:51 +03:00
Tony Kovanen
54726105cb Fixed handshake object address property and made the test case more strict. 2014-07-19 04:43:03 +03:00
Guillermo Rauch
3d9e52cf93 Merge branch 'master' of github.com:Automattic/socket.io 2014-07-17 12:20:17 -07:00
Guillermo Rauch
ad74f2ff88 package: bump engine.io 2014-07-17 12:17:46 -07:00
Guillermo Rauch
cf1c1273b3 Merge pull request #1682 from kevin-roark/fix/disconnect-connectbuffer-crash
Fixed the failing test where server crashes on disconnect involving connectBuffer
2014-07-16 10:58:54 -07:00
Kevin Roark
1f43c4abb5 Fixed the failing test where server crashes on disconnect involving connectBuffer
Source of bug: after connection to nsp '/', the socket's connectBuffer
was being deleted. On attempt to reconnect to a different namespace,
the connect buffer was deleted and we attempted to push to it. Instead
of the deleting the connect buffer, it is now emptied.
2014-07-16 08:35:16 -07:00
Guillermo Rauch
d6e6e8a2f8 Merge pull request #1673 from bryanburgers/patch-1
Fix repo in package.json
2014-07-15 18:25:59 -07:00
Guillermo Rauch
fbd36b613d npmignore: ignore .gitignore (fixes #1607) 2014-07-15 10:55:34 -07:00
Guillermo Rauch
480b1a05bd test: added failing case for socket.disconnect and nsps 2014-07-15 10:52:23 -07:00
Bryan Burgers
ef729b72b4 Fix repo in package.json 2014-07-09 07:28:45 -05:00
Thanasis Polychronakis
63e197083b update README http ctor to createServer() 2014-07-01 10:41:53 +03:00
Guillermo Rauch
968e94e42b Merge pull request #1655 from ysmood/fix_etag_header
We should use the standard http protocol to handler the etag header
2014-06-30 23:32:23 -07:00
Guillermo Rauch
c18ed5fd4d Merge pull request #1646 from narcisoguillen/close_sio
Close sio
2014-06-30 19:10:26 -07:00
Narciso Guillen
1f7da938bd Improve Close documentation 2014-06-30 15:57:21 -05:00
Narciso Guillen
4b89bce182 use ephemeral ports 2014-06-30 15:49:08 -05:00
Yad Smood
8c19eef07a fix: We should use the standard http protocol to handler the etag
header.
2014-06-29 21:42:57 +08:00
Guillermo Rauch
662b30669b Merge pull request #1653 from acusti/patch-1
Override default browser font-family for inputs
2014-06-28 10:55:22 -07:00
Andrew Patton
001373ee17 Override default browser font-family for inputs
For consistent typography, explicitly declare font-family stack for `input` in addition to `html` (in Chrome and Safari on mac, the input will otherwise use default font for such elements, like Lucida Grande)
2014-06-28 13:14:33 -04:00
Guillermo Rauch
246f3bb5c3 Merge pull request #1648 from kevin-roark/update/has-binary-data
update has-binary-data to 1.0.3
2014-06-23 20:20:39 -07:00
Kevin Roark
68d06ec94c update has-binary-data to 1.0.3 2014-06-23 20:19:26 -07:00
Narciso Guillen
a1feca1bd3 Add close specs 2014-06-23 21:03:31 -05:00
Narciso Guillen
968105a239 Add ability to stop the http server even if not created inside socket.io 2014-06-23 21:03:12 -05:00
Narciso Guillen
2e8e26613a Update README 2014-06-23 20:02:39 -05:00
Narciso Guillen
fbdb94d146 make sure server gets close 2014-06-23 19:55:02 -05:00
Tony Kovanen
55572122f3 Merge pull request #1642 from rase-/add/test
Duplicate events test for `reconnect_failed`
2014-06-21 17:28:37 +03:00
Tony Kovanen
a1170a3aa6 Bump client 2014-06-21 17:26:55 +03:00
Tony Kovanen
0954301d7e Add test case for checking that reconnect_failed is fired only once upon failure 2014-06-21 17:14:15 +03:00
Guillermo Rauch
328a9df8eb package: bump socket.io-parser for component-emitter dep fix
cc @davglass @reid
2014-06-20 16:57:54 -07:00
Guillermo Rauch
d99e30fca7 Release 1.0.6 2014-06-19 14:57:50 -07:00
Guillermo Rauch
561dd6fd79 package: bump engine.io for utf8 fix (fixes #1622) 2014-06-19 14:51:37 -07:00
Guillermo Rauch
e9e2a91cea package: bump socket.io-client 2014-06-19 08:05:38 -07:00
Guillermo Rauch
8a3a111a7f Merge pull request #1635 from rase-/add/test
Test for duplicate events on manual reconnect
2014-06-18 15:54:23 -07:00
Tony Kovanen
bd87e4dc35 Bump socket.io-client to latest commit so that duplicate events test passes 2014-06-19 01:52:34 +03:00
Tony Kovanen
71c253e992 Added test for duplicate events after manual reconnects 2014-06-19 01:49:00 +03:00
Guillermo Rauch
a5cf4f57a0 Release 1.0.5 2014-06-17 18:14:44 -07:00
Guillermo Rauch
a079cbc7f9 client: fixes #1632 2014-06-17 18:07:30 -07:00
Guillermo Rauch
14a9fdb64f package: bump engine.io 2014-06-16 08:36:01 -07:00
Thanasis Polychronakis
55fb100fc0 http.Server is a constructor
...and thus requires the `new` keyword
2014-06-14 13:52:36 +03:00
Guillermo Rauch
6159df3937 fixed client 2014-06-13 13:04:50 -07:00
Guillermo Rauch
6f7bab5dfd Merge pull request #1578 from kevin-roark/add/emit-buffer-test
added the client emit-buffer test
2014-06-13 10:10:40 -07:00
Guillermo Rauch
7d2b44e176 index: fix typo [thanks @yanatan16] 2014-06-11 10:42:48 -07:00
Tony Kovanen
0b5fdf995a Merge pull request #1603 from nkzawa/patch-2
Add removeListener to blacklisted events
2014-06-08 14:40:25 +03:00
Naoyuki Kanezawa
a66bea5b33 add removeListener to blacklisted events 2014-06-08 20:34:50 +09:00
Guillermo Rauch
a1a88aaaaf Merge pull request #1600 from poldridge/master
Update index.js
2014-06-06 22:36:19 -07:00
poldridge
3f817c3a18 Update index.js
Added missing hasOwnProperty check. socket.io breaks without it when Object.prototype has been extended.
2014-06-06 22:08:58 -07:00
Guillermo Rauch
99bbd74d14 Merge pull request #1582 from kevin-roark/add/clearer-example-instructions
Add/clearer example instructions
2014-06-02 20:44:34 -07:00
Kevin Roark
398511ddee Merge branch 'upstream' into add/clearer-example-instructions 2014-06-02 20:28:42 -07:00
Kevin Roark
fdf7937815 clearer instructions to install chat example 2014-06-02 20:28:19 -07:00
Guillermo Rauch
475909e642 Release 1.0.4 2014-06-02 20:08:33 -07:00
Guillermo Rauch
95acec8b94 package: bump socket.io-client 2014-06-02 20:07:07 -07:00
Kevin Roark
5812ddf2b0 added the client emit-buffer test 2014-06-01 23:20:42 -07:00
Guillermo Rauch
1bbc3951bd Release 1.0.3 2014-05-31 18:34:50 -07:00
Guillermo Rauch
039eed2c2a package: bump socket.io-client 2014-05-31 09:53:25 -07:00
Guillermo Rauch
6de022b180 Merge pull request #1565 from kevin-roark/add/binary-ack
Add/binary ack
2014-05-31 09:50:19 -07:00
Guillermo Rauch
a06331d29f travis fix 2014-05-30 21:37:22 -07:00
Guillermo Rauch
e639685370 fix travis 2014-05-30 21:23:55 -07:00
Guillermo Rauch
1f2e681ce2 package: bump socket.io-parser for binary ack fix 2014-05-30 21:11:57 -07:00
Kevin Roark
397944fcbe big file tests 2014-05-30 20:40:44 -07:00
Kevin Roark
27dada65b9 distinction between ACK and BINARY_ACK 2014-05-30 18:42:23 -07:00
Guillermo Rauch
99f1ac9aae Merge pull request #1563 from rase-/fix/no-disconnect-fired-for-nsp
Fix namespace iterator in disconnect
2014-05-30 16:40:59 -07:00
Tony Kovanen
ee8d0fbae0 Fix namespace iterator in disconnect 2014-05-31 02:25:28 +03:00
Guillermo Rauch
8e08a6d419 Merge pull request #1562 from rase-/add/utf8-tests
Add test case for emitting multibyte chars
2014-05-30 15:48:34 -07:00
Tony Kovanen
318ae87f50 Add test case for emitting multibyte chars 2014-05-31 01:45:31 +03:00
Guillermo Rauch
2c1b61148d Merge branch 'master' of github.com:automattic/socket.io 2014-05-30 14:14:12 -07:00
Guillermo Rauch
507054c0a8 package: bump engine.io for utf8 binary fix 2014-05-30 14:09:54 -07:00
Tony Kovanen
dfceb006d7 Merge pull request #1554 from grant/master
Fix xss vulnerability in example chat app
2014-05-30 12:15:12 +03:00
Grant Timmerman
4d83456f74 Fix xss vulnerability in example chat app 2014-05-30 02:03:33 -07:00
Tony Kovanen
201aad83b1 Merge pull request #1540 from grant/master
Make chat example wrap long words (no overflow)
2014-05-30 12:02:15 +03:00
Grant Timmerman
72eb61d01f Make chat example wrap long words (no overflow) 2014-05-30 01:44:27 -07:00
Tony Kovanen
163a2a696e Merge pull request #1543 from mohnish/patch-1
Remove obsolete message from README file
2014-05-29 21:33:36 +03:00
Guillermo Rauch
199a479ebc Merge pull request #1545 from overra/patch-1
Use cleanInput() on incoming messages
2014-05-28 20:47:20 -07:00
Guillermo Rauch
d383ff9662 Merge pull request #1546 from hiddenmin/patch-1
Update Readme.md
2014-05-28 19:42:39 -07:00
Amin Cheloh
416b550189 Update Readme.md
socket.io-adapter link
2014-05-29 09:41:37 +07:00
Adam Snodgrass
536b338a01 Use cleanInput() on incoming messages
This prevents XSS if one were to send messages using socket.io from the console.
2014-05-28 20:35:24 -05:00
Mohnish Thallavajhula
a06ae10895 Remove obsolete message from README file 2014-05-28 17:10:50 -07:00
Guillermo Rauch
35a85084b1 Release 1.0.2 2014-05-28 13:24:59 -07:00
Guillermo Rauch
0c2b44a846 package: bump parser for windows fix 2014-05-28 13:23:51 -07:00
Guillermo Rauch
0f6ee2dbd9 travis 2014-05-28 12:56:10 -07:00
Guillermo Rauch
68ac0d6d24 Release 1.0.1 2014-05-28 10:32:31 -07:00
Guillermo Rauch
00ef9ca652 Release 1.0.0 2014-05-28 10:19:24 -07:00
Guillermo Rauch
2febbce87d Merge pull request #1530 from kevin-roark/update/has-binary-data
bump has-binary-data
2014-05-24 15:19:48 -07:00
Kevin Roark
31c45862cb bump has-binary-data 2014-05-24 14:14:59 -05:00
Guillermo Rauch
809e2bc3f8 Merge pull request #1529 from rase-/add/bc
Added socket.handshake BC object
2014-05-24 11:08:00 -07:00
Tony Kovanen
10adcb089e Added socket.handshake BC object 2014-05-24 17:02:47 +03:00
Guillermo Rauch
5bc75ea944 Release 1.0.0-pre5 2014-05-22 09:35:32 -07:00
Guillermo Rauch
cd4f6ad5e9 package: bump socket.io-client for parser fixes 2014-05-22 09:32:42 -07:00
Guillermo Rauch
54e6c79014 package: bump engine.io 2014-05-22 09:25:58 -07:00
Guillermo Rauch
237b234cab Release 1.0.0-pre4 2014-05-19 16:02:54 -07:00
Guillermo Rauch
547440605d package: bump client 2014-05-19 16:02:31 -07:00
Guillermo Rauch
d763c8b6ea Release 1.0.0-pre3 2014-05-17 15:40:40 -07:00
Guillermo Rauch
5d210ac46c package: bump parser 2014-05-17 14:02:57 -07:00
Guillermo Rauch
ea89e520bc package: bump engine.io 2014-05-16 16:57:41 -07:00
Guillermo Rauch
c8bf064b10 Merge pull request #1513 from hallucynogenyc/patch-1
Update for new npm check
2014-05-06 10:15:33 -04:00
hallucynogenyc
08fe191211 Update for new npm check
Npm will now throw a warning when installing a package:

npm WARN package.json socket.io@1.0.0-pre2 No repository field.

If the repository field is not present.
2014-05-06 16:14:50 +02:00
Guillermo Rauch
0842729c1f test: temporarily removing parser test 2014-04-28 11:16:59 -07:00
Guillermo Rauch
9720c76d10 Release 1.0.0-pre2 2014-04-27 19:40:33 -07:00
Guillermo Rauch
0f127d2b7d package: bump engine.io 2014-04-27 19:23:07 -07:00
Guillermo Rauch
e87e9e18e1 package: bump parser 2014-04-27 18:54:53 -07:00
Guillermo Rauch
46351d38b8 Merge pull request #1489 from kevin-roark/add/protocol-check
added test that server and client using same protocol
2014-04-14 13:11:04 -07:00
Kevin Roark
ce68fb3105 Merge branch 'upstream' into add/protocol-check 2014-04-14 12:43:01 -04:00
Guillermo Rauch
94905500e4 Merge pull request #1467 from rase-/add/set-backwards-compatibility
Added backwards compatible settability of engine.io maxHttpBufferSize
2014-04-13 12:25:36 -07:00
Tony Kovanen
f830899e39 Added backwards compatible settability of engine.io maxHttpBufferSize
Updated readme
2014-04-12 12:02:52 +03:00
Guillermo Rauch
3444f017bc Merge pull request #1492 from kevin-roark/add/query-test
Added a test to check access to client query params
2014-04-11 10:57:04 -07:00
Kevin Roark
0588dc0fc4 Added a test to check access to client query params
It fails with the current upstream client! There is a pending PR to
make this test pass though.
2014-04-11 13:19:19 -04:00
Guillermo Rauch
57425ab1dd Merge pull request #1485 from rase-/add/origins
Added support for setting allowed origins
2014-04-11 09:46:37 -07:00
Tony Kovanen
463d7a16a1 Moved the origins checking callback outside the origins getter/setter function. 2014-04-11 19:39:10 +03:00
Tony Kovanen
5d74847123 Updated README to include origins 2014-04-11 01:29:37 +03:00
Kevin Roark
f8b4d87331 added test that server and client using same protocol 2014-04-10 14:45:32 -04:00
Tony Kovanen
e9928b2b1d Switched to async allowRequest callback in engine.io for setting the allowed origins 2014-04-10 21:02:20 +03:00
Tony Kovanen
d33553a4bd Added support for setting allowed origins 2014-04-09 22:34:53 +03:00
Guillermo Rauch
45a98970d7 added information about logging 2014-03-28 11:51:54 -03:00
Guillermo Rauch
0b4e4f6a67 Merge pull request #1464 from rase-/add/set-backwards-compatibility
Set function for BC
2014-03-25 20:09:16 -03:00
Tony Kovanen
656047536a The set function in server can be used to set some attributes for backwards compatibility 2014-03-26 00:04:22 +02:00
Guillermo Rauch
97b7ab4fe2 Merge pull request #1462 from nicolagreco/patch-1
Mistake in callback call 'done' instead of 'next' in docs
2014-03-24 22:38:02 -03:00
Nicola Greco
6a435ce677 Mistake in callback call 'done' instead of 'next' in docs 2014-03-25 01:02:46 +00:00
Guillermo Rauch
6aa553b211 Merge branch 'master' of github.com:LearnBoost/socket.io 2014-03-24 14:44:00 -03:00
Guillermo Rauch
024af23b2c package: bump client 2014-03-24 14:43:37 -03:00
Guillermo Rauch
b50d9f8f5d Merge pull request #1443 from kevin-roark/add/simple-tests
added some new tests, including binary with acks
2014-03-24 14:21:19 -03:00
Kevin Roark
874c194210 Merge branch 'upstream' into add/simple-tests
Conflicts:
	package.json
2014-03-24 13:03:43 -04:00
Guillermo Rauch
f537560bcc package: bump socket.io-parser 2014-03-18 18:28:49 -03:00
Guillermo Rauch
7197d6a29d rebuild 2014-03-18 17:16:38 -03:00
Guillermo Rauch
8dba96511d package: rollback socket.io-parser to fix acks 2014-03-18 16:45:48 -03:00
Guillermo Rauch
f8d1d33dfa Merge branch 'master' of github.com:LearnBoost/socket.io
Conflicts:
	package.json
2014-03-18 16:34:49 -03:00
Guillermo Rauch
736106a9e7 package: bump engine.io 2014-03-18 16:31:22 -03:00
Guillermo Rauch
f5a8ac293a Merge pull request #1452 from kevin-roark/update/parser-dependency
updated parser dependency
2014-03-15 19:35:35 -02:00
Kevin Roark
afc83ad65a Merge branch 'upstream' into add/simple-tests
Conflicts:
	package.json
2014-03-15 17:32:27 -04:00
Kevin Roark
b5f90923a2 updated parser dependency 2014-03-15 17:30:47 -04:00
Guillermo Rauch
c574f5f959 Merge pull request #1451 from elisee/patch-1
Fix // … to be /* … */ in README.md
2014-03-15 17:57:01 -02:00
elisee
ba339cc460 Fix // … to be /* … */ 2014-03-15 20:25:00 +01:00
Guillermo Rauch
aee4dd9a6d package: bump expect.js 2014-03-15 10:39:21 -03:00
Guillermo Rauch
ad86129437 Release 1.0.0-pre 2014-03-15 10:36:51 -03:00
Guillermo Rauch
c8eda77da3 package: fix versions 2014-03-15 10:33:02 -03:00
Guillermo Rauch
a4fabba781 Readme: tweak 2014-03-15 10:23:25 -03:00
Guillermo Rauch
c19d2692e2 package: bump engine.io 2014-03-14 19:39:10 -03:00
Guillermo Rauch
36ad8e87eb package: bump socket.io-adapter 2014-03-14 15:05:43 -03:00
Kevin Roark
7d4aa670ad bumped parser dependency 2014-03-13 10:49:31 -04:00
Kevin Roark
620f94a007 Merge branch 'upstream' into add/simple-tests
Conflicts:
	package.json
2014-03-12 20:33:01 -04:00
Guillermo Rauch
f808c377b0 package: bump engine.io 2014-03-12 15:47:29 -03:00
Guillermo Rauch
41c5b37ac7 bump engine.io 2014-03-11 11:53:42 -03:00
Guillermo Rauch
c972153669 bump client 2014-03-10 20:09:56 -03:00
Kevin Roark
4823d20cf1 Merge branch 'upstream' into add/simple-tests
Conflicts:
	package.json
2014-03-08 20:58:41 -05:00
Guillermo Rauch
44a79f9cee server: make Server#adapter work after construction 2014-03-07 18:33:36 -03:00
Guillermo Rauch
81e8a0c3a5 added support for volatile packets 2014-03-07 04:09:43 -06:00
Guillermo Rauch
adffabeee3 style 2014-03-07 03:41:22 -06:00
Guillermo Rauch
79dd06a767 socket: fix flags api state 2014-03-07 03:32:27 -06:00
Guillermo Rauch
93df3c47cc Readme; document Socket#id 2014-03-07 00:43:40 -06:00
Guillermo Rauch
2a3a5a01a2 Readme: document Socket#join and Socket#leave 2014-03-07 00:39:39 -06:00
Guillermo Rauch
dd8745ece2 Readme: document to multiple-call situation 2014-03-07 00:33:54 -06:00
Guillermo Rauch
4615e932c1 Readme: document Socket#to and Socket#in 2014-03-07 00:33:05 -06:00
Guillermo Rauch
7e96f0a1ff Readme: document Socket#emit 2014-03-07 00:31:01 -06:00
Guillermo Rauch
8df80ee91c move adapter out 2014-03-06 22:49:38 -06:00
Kevin Roark
612d35194f updated parser dependency 2014-03-06 18:41:43 -05:00
Kevin Roark
a5ff1d854e added some new tests, including binary with acks 2014-03-06 16:58:21 -05:00
Guillermo Rauch
0c8ed9547c package: introduce proper engine.io version 2014-03-06 12:11:46 -08:00
Guillermo Rauch
8104694fdf package: bump parser 2014-03-04 23:29:22 -08:00
Guillermo Rauch
6be582db3d package: bump client 2014-03-04 00:25:24 -08:00
Guillermo Rauch
12733a8759 test: fix global leakage 2014-03-03 14:22:51 -08:00
Guillermo Rauch
5e28161322 Merge pull request #1440 from kevin-roark/add/binary-broadcasting
Added binary support to broadcasting of events
2014-03-02 20:53:37 -08:00
Kevin Roark
c2bf0ea700 Added binary support to broadcasting of events
lib/namespace.js previously was not considering whether an event had
binary data and was giving all events parser.EVENT type -- now it uses
the has-binary-data module to set the event type appropriately.

Then, after this fix there was a problem with lib/adapter.js -- because
socket.io-parser modifies the packet object in its encoding, the sockets
after the 1st in a broadcast were not getting the correct data. To fix
this, the data is encoded once in adapter, and then the encoded data
is passed to each of the sockets.

lib/socket.js and lib/client.js were updated to allow for the above. The
.packet method of each now takes an optional second "preEncoded" parameter
-- if this is true, then client skips the encoding and just writes the
packet argument directly to engine.

test/socket.io.js was updated to add two new tests that test
multi-messaging of events with binary data.
2014-03-02 22:15:16 -05:00
Guillermo Rauch
571f3a663c package: bump socket.io-client for new build 2014-03-01 10:18:33 -08:00
Guillermo Rauch
d293e3be7c version badge 2014-03-01 09:00:34 -08:00
Guillermo Rauch
e2a5e4b1f2 package: adjust socket.io-client 2014-03-01 08:55:50 -08:00
Guillermo Rauch
7b4c8c67c2 package: bump parser 2014-03-01 08:55:05 -08:00
Guillermo Rauch
e280e17094 Merge pull request #1432 from kevin-roark/add/better-binary-events
Updated protocol-facing code for new binary protocol
2014-03-01 08:53:49 -08:00
Guillermo Rauch
947d7b4ea5 Merge pull request #1437 from keyosk/master
Update chat example
2014-03-01 08:21:53 -08:00
Cody Massin
318d62e5ad When displaying leave and join messages show a message with an updated participants count.
Signed-off-by: Cody Massin <keyosk@gmail.com>
2014-03-01 00:20:51 -08:00
Kevin Roark
fc34c7d7a4 Updated protocol-facing code to reflect newest parser
Socket.io-parser now has a class-based Encoder and Decoder scheme,
so client.js was changed appropriately.

The main difference is that most of the logic for interpreting packets
is now isolated to parser, and client receives a 'decoded' event when
parser has a reconstructed packet ready to go.
2014-02-27 17:54:02 -05:00
Kevin Roark
449c28ce1c Updated protocol-facing code for new binary protocol
This is a squash of four boring commits. The gist is that client.js
encoding and decoding stuff was updated to take an array of encoded packets
to write, and to handle sequences of binary packets to decode. There was
also merging done with upstream. All tests are passing.
2014-02-26 13:45:47 -05:00
Guillermo Rauch
3faca287a5 chat: forward 3000 2014-02-24 16:54:48 -08:00
Guillermo Rauch
266278d14c prettify 2014-02-24 16:46:23 -08:00
Guillermo Rauch
d286ba2064 rename app->index 2014-02-24 16:28:04 -08:00
Guillermo Rauch
d4ec1b6ff0 use shorthand io call 2014-02-24 16:27:46 -08:00
Guillermo Rauch
49f11f9cf5 README: move to index 2014-02-24 16:27:37 -08:00
Guillermo Rauch
05fd23ddda Merge pull request #1430 from kevin-roark/fix/has-binary-dependency
fixed the has-binary-data dependency
2014-02-21 14:19:35 -08:00
Kevin Roark
d21b1f36a3 fixed the has-binary-data dependency 2014-02-21 17:10:53 -05:00
Guillermo Rauch
573b32cc7d package: bump client 2014-02-21 13:32:12 -08:00
Guillermo Rauch
16d1afc7fc Merge pull request #1426 from brishin/binary
Binary
2014-02-21 13:02:26 -08:00
Kevin Roark
675830e726 updated socket.io-client dependency 2014-02-20 17:21:39 -05:00
Kevin Roark
b1c971507b updated engine and -parser dependencies 2014-02-19 19:54:31 -05:00
Kevin Roark
8c3ca99e7c merged binary with upstream's new chat app 2014-02-19 18:03:36 -05:00
Kevin Roark
beab053123 anonymous function style correct 2014-02-19 17:57:59 -05:00
Kevin Roark
745ee03102 Added binary support to socket.io
This is a squash of about 25 commits, and here is a summary:

adamreis added initial binary test with the doge image.

kevin-roark updated binary tests and wrote some binary encoding protocol.

kevin-roark replaced the custom binary encoding with msgpack because we
have to handle arbitrary json that contains binary.

adamreis added some 'crazy' tests for emmiting and receiving events with
several types of data.

kevin-roark updated client.js to use socket.io-protocol's async encoding

Did a bunch of upstream merging.
2014-02-19 13:46:39 -05:00
Guillermo Rauch
69de792c03 Merge pull request #1427 from grant/upstream
Example: Chat -- Welcome message is always on top. Click now focuses input.
2014-02-18 21:14:53 -08:00
Grant Timmerman
d037d6cb38 Redefined input-focus click areas 2014-02-18 21:08:43 -08:00
Grant Timmerman
e06ea11c27 Welcome message is always on top. Click now focuses input. 2014-02-18 20:43:59 -08:00
Guillermo Rauch
daf8df8f5c Merge pull request #1425 from Aaron1011/node_11
Test on Node 0.11
2014-02-18 17:00:06 -08:00
Guillermo Rauch
ff2476c7a5 Merge pull request #1415 from grant/upstream
Example: Chat
2014-02-18 15:51:51 -08:00
Aaron Hill
fc77c0faca Test on Node 0.11 2014-02-18 12:31:07 -05:00
Grant Timmerman
e0a85a90aa Changed hash function after testing it on generated lists of random usernames 2014-02-17 13:50:43 -08:00
Grant Timmerman
3aa3213b13 Moved colors to client with hash fn, cleaned up app.js 2014-02-17 13:41:21 -08:00
Grant Timmerman
575ff2ecfc Fixed scrollbar height, fixed "undefined is typing", cleaned up fade effect 2014-02-16 12:12:02 -08:00
Grant Timmerman
852a9d34df Added X is typing functionality 2014-02-16 02:50:33 -08:00
Grant Timmerman
8a3781499d Reorganized event system, added log event, and changed formatting of chat 2014-02-16 01:05:41 -08:00
Grant Timmerman
ab60d166ac Added basic chatroom html 2014-02-15 23:31:00 -08:00
Grant Timmerman
f7838635a7 Added basic login page html for the new design 2014-02-15 23:00:20 -08:00
Grant Timmerman
cfb2a26d4f Updated package.json, added numUsers int on server, and used io shorthand notation 2014-02-14 21:29:08 -08:00
Guillermo Rauch
09cfb17731 *: remove unused client dir and symlink WARN 2014-02-14 10:34:24 -08:00
Guillermo Rauch
4cd4381b80 lib: bc compatibility 2014-02-13 14:12:59 -08:00
Guillermo Rauch
d65ec8d649 package: bump socket.io-client 2014-02-12 16:43:08 -08:00
Guillermo Rauch
e16ac61b82 package: bump socket.io-client 2014-02-12 16:28:35 -08:00
Guillermo Rauch
d17f5ce914 package: use a specific debug 2014-02-12 14:21:04 -08:00
Guillermo Rauch
1982afa481 package: serve a working socket.io-client 2014-02-12 14:16:32 -08:00
Grant Timmerman
1860aa41ee Removed extra lines, removed extra html 2014-02-11 21:46:59 -08:00
Grant Timmerman
598a140ad4 Update styles and formatting 2014-02-11 21:30:07 -08:00
Grant Timmerman
b8f6d4054c Added more friendly username input interface 2014-02-11 21:11:58 -08:00
Grant Timmerman
450d408ed6 Updated code style 2014-02-11 18:18:54 -08:00
Grant Timmerman
0023aed4c3 Changed tabs to spaces, removed screenshot, and updated README 2014-02-11 17:13:44 -08:00
Grant Timmerman
f99cdc9339 Updated package.json and Readme 2014-02-11 16:22:01 -08:00
Grant Timmerman
999b8bc387 Updated screenshot 2014-02-11 16:16:25 -08:00
Grant Timmerman
95d19e285c Removed external npm socket.io and now using local socket.io module 2014-02-11 13:09:46 -08:00
Grant Timmerman
9f8b1a2e1e Removed .gitignore in the chat example 2014-02-11 13:04:14 -08:00
Grant Timmerman
0c5e3eb5cf Merge branch 'master' of https://github.com/LearnBoost/socket.io into upstream 2014-02-11 13:00:20 -08:00
Grant Timmerman
eca3316620 Removed zuul yml 2014-02-11 12:59:17 -08:00
Grant Timmerman
29df46ae07 Added chat example 2014-02-11 12:48:55 -08:00
Guillermo Rauch
980b6a7c40 package: bump engine.io 2014-02-09 11:18:49 -08:00
Guillermo Rauch
c0393fce20 Merge pull request #1399 from lzyzsd/master
fix captcha in comment
2014-02-08 12:13:01 -08:00
Guillermo Rauch
093f5f7186 style 2014-02-08 12:12:47 -08:00
Guillermo Rauch
1f0f209d5e Merge pull request #1411 from get/server-client-file
change index to read build file from client
2014-02-08 12:11:57 -08:00
GK
fc61a37a6d change index to read build file from client 2014-02-08 11:18:07 -08:00
Guillermo Rauch
bf8761fb9b Merge pull request #1410 from brishin/test
Fix `npm test`
2014-02-07 15:24:45 -08:00
Brian Donghee Shin
3dcba2859c Fix npm test 2014-02-07 15:23:22 -08:00
Guillermo Rauch
c73e01485d Merge pull request #1403 from nkzawa/patch-1
middlewares of main namespace should be called first
2014-02-03 14:00:14 -08:00
Naoyuki Kanezawa
a3e1b0658f middlewares of main namespace should be called first 2014-02-04 04:00:24 +09:00
Guillermo Rauch
3cf6a0949b Merge pull request #1402 from gdi2290/patch-1
update copyright year
2014-02-03 06:52:08 -08:00
PatrickJS
a98b8abe97 update copyright year 2014-02-03 02:08:42 -08:00
Bruce Lee
db429864f6 fix captcha 2014-01-24 21:29:55 +08:00
Guillermo Rauch
7d5612eed7 Merge pull request #1395 from nulltask/patch-1
index: remove send dep
2014-01-15 10:22:41 -08:00
Seiya Konno
3efcd52674 index: remove send dep 2014-01-16 03:18:39 +09:00
Guillermo Rauch
8c0b60791c gitignore: added coverage 2014-01-10 11:47:55 -03:00
Guillermo Rauch
32fe383e70 package: remove send dependency 2014-01-10 11:47:24 -03:00
Guillermo Rauch
6305ebe8aa test: extend client serving tests 2014-01-10 11:47:04 -03:00
Guillermo Rauch
2b1a5afe6c index: simplify and speed up client serving 2014-01-10 11:46:45 -03:00
Guillermo Rauch
84bf735e4d add test coverage 2014-01-09 13:09:26 -03:00
Guillermo Rauch
142c73c9a1 index: remove SIO_COV env 2014-01-09 13:01:08 -03:00
Guillermo Rauch
07cf9395a0 package: bump engine.io 2014-01-02 08:00:04 -03:00
Guillermo Rauch
7ed789d381 package: remove ~ 2014-01-02 07:40:44 -03:00
Guillermo Rauch
48936231ea index: add support for string port numbers 2013-12-26 21:30:33 -03:00
Guillermo Rauch
2b5183b369 socket: revert onclose reason 2013-12-25 13:15:18 -03:00
Guillermo Rauch
14c71c2e72 socket: fix onclose reason 2013-12-25 13:13:02 -03:00
Guillermo Rauch
03db6a62e7 Readme: document use 2013-12-24 21:46:23 -03:00
Guillermo Rauch
83208b6e11 socket: add conn, client, request getters 2013-12-24 21:36:48 -03:00
Guillermo Rauch
036faa7d89 Readme: fix 2013-12-24 21:02:15 -03:00
Guillermo Rauch
7b2a71ac4f server: add listen 2013-12-24 20:49:21 -03:00
Guillermo Rauch
da844159d9 namespace: jshint friendly usage of reserved keyword for backwards-compatibility 2013-12-24 20:10:16 -03:00
Guillermo Rauch
baea55009b Readme: document usage with node 2013-12-24 20:08:47 -03:00
Guillermo Rauch
198efb0957 Readme: clarify engine.io options 2013-12-24 20:07:56 -03:00
Guillermo Rauch
f0e88265d6 Readme: added example of using 1.0 and koajs 2013-12-24 20:05:24 -03:00
Guillermo Rauch
760e1b5cda Readme: fix 2013-12-24 20:01:56 -03:00
Guillermo Rauch
ecca4ee738 use serveClient in favor of static for broader jshint compliance 2013-12-24 20:00:46 -03:00
Guillermo Rauch
d31aafa5fd socket: fix style 2013-12-24 19:56:10 -03:00
Guillermo Rauch
c545e3b963 lib: fix style 2013-12-24 19:56:01 -03:00
Guillermo Rauch
af66e5df4e client: fix style 2013-12-24 19:55:52 -03:00
Guillermo Rauch
a86994f693 index: syntax 2013-12-24 19:51:53 -03:00
Guillermo Rauch
430670f136 Merge pull request #1313 from tylermcginnis33/patch-1
Remove unnecessary comma from documentation
2013-12-09 08:27:02 -08:00
Guillermo Rauch
f65966d858 Merge pull request #1220 from balupton/patch-1
Removed 0.6 from travis (no longer supported by socket.io deps), added 0.10
2013-12-09 08:16:38 -08:00
Guillermo Rauch
2f3f54fb38 updated history 2013-12-09 13:03:37 -03:00
Guillermo Rauch
f0cc5aa834 package: bump engine.io 2013-12-09 13:00:02 -03:00
Guillermo Rauch
340281152f LICENSE: update 2013-12-09 00:28:51 -03:00
Guillermo Rauch
5f247ca38e package: remove optionalDependencies 2013-12-09 00:27:45 -03:00
Tyler McGinnis
cbabf0719e Remove unnecessary comma from documentation
A comma is used when there are three or more items in a series or you are separating two or more independent clauses.
2013-09-11 19:10:46 -07:00
Benjamin Arthur Lupton
6a11d09590 Removed 0.6 from travis, added 0.10
Also stringified the versions as they should be, as it is a yaml file so `0.10` becomes `0.1`, so for versions we should use strings - `"0.10"` stays `0.10`
2013-04-19 12:45:47 +10:00
Guillermo Rauch
64f6b244b6 Merge pull request #1189 from kaosdynamics/patch-1
Fix socket.io-client repository name
2013-03-19 16:35:17 -07:00
Kaos Dynamics
9ad1c2f3ac Fix socket.io-client repository name 2013-03-15 00:10:21 +01:00
Guillermo Rauch
242d02dee5 Merge pull request #1188 from MatthewMueller/master
fix install for 1.0
2013-03-13 17:57:50 -07:00
Matthew Mueller
3bd5455b1a Update package.json 2013-03-13 17:14:47 -07:00
Guillermo Rauch
7cc56a51a8 package: bumped engine.io 2013-02-22 10:55:26 -08:00
Guillermo Rauch
0d5200ed69 Readme: fix 2013-01-28 07:53:30 -08:00
Guillermo Rauch
abf798e2bb Readme: note 2013-01-28 07:51:55 -08:00
Guillermo Rauch
2102eb4bb3 Readme: added listen to examples 2013-01-28 07:51:14 -08:00
Guillermo Rauch
cef1583a64 test: middleware tests 2012-12-24 19:50:49 -03:00
Guillermo Rauch
5f843feb90 namespace: make sure not to fire connection if underlying client closed after next is called from a middleware 2012-12-24 19:50:25 -03:00
Guillermo Rauch
01a06b2b62 Makefile: change slow param 2012-12-24 19:50:13 -03:00
Guillermo Rauch
46d069b3cc test: added room tracking test 2012-12-24 15:07:23 -03:00
Guillermo Rauch
708af3f803 README: renamed joined to rooms 2012-12-24 15:07:13 -03:00
Guillermo Rauch
0881dfbdce socket: rename joined to rooms 2012-12-24 15:07:04 -03:00
Guillermo Rauch
c54011b6a1 Readme: document Namespace#connected 2012-12-23 23:25:17 -03:00
Guillermo Rauch
f605b365b4 test: added broadcasting / namespace emit tests 2012-12-23 23:24:35 -03:00
Guillermo Rauch
1ec766799f test: fix helper to take options 2012-12-23 23:24:19 -03:00
Guillermo Rauch
67f7d5749b adapter: initial memory impl 2012-12-23 23:23:05 -03:00
Guillermo Rauch
95d8e7531c socket: keep track of socket in connected hash 2012-12-23 23:21:50 -03:00
Guillermo Rauch
2e71357221 socket: added leaveAll 2012-12-23 23:21:37 -03:00
Guillermo Rauch
ef96e3b07f socket: added leave 2012-12-23 23:21:18 -03:00
Guillermo Rauch
6046c385b9 socket: added join 2012-12-23 23:21:07 -03:00
Guillermo Rauch
e8d11924aa socket: added in 2012-12-23 23:20:58 -03:00
Guillermo Rauch
eb0213882f socket: fix emit 2012-12-23 23:20:46 -03:00
Guillermo Rauch
de8e746959 socket: rooms and flags are now hashes 2012-12-23 23:20:26 -03:00
Guillermo Rauch
dc173330e5 socket: fix flags 2012-12-23 23:20:13 -03:00
Guillermo Rauch
d65635d212 socket: rename rooms to joined 2012-12-23 23:20:03 -03:00
Guillermo Rauch
dd0fd539e6 namespace: fix emit 2012-12-23 23:19:05 -03:00
Guillermo Rauch
5d4f90de47 namespace: make in able to track multiple rooms 2012-12-23 23:18:48 -03:00
Guillermo Rauch
59c8c34ceb namespace: fix flags 2012-12-23 23:18:38 -03:00
Guillermo Rauch
bcfec6df76 namespace: added connected hash 2012-12-23 23:18:26 -03:00
Guillermo Rauch
dbba592dfa namespace: implement own flags 2012-12-23 23:18:14 -03:00
Guillermo Rauch
d411dec5a4 index: rename adaptor to adapter 2012-12-23 23:18:01 -03:00
Guillermo Rauch
ab5a226f3e README: rename Adaptor to Adapter 2012-12-23 23:17:48 -03:00
Guillermo Rauch
fb857bd8b4 index: added Server#adaptor 2012-12-18 18:09:41 -03:00
Guillermo Rauch
2e5fdb65bd README: improved getters/setters docs and added Adaptor section 2012-12-18 18:07:30 -03:00
Guillermo Rauch
b4f12ea2f9 README: document Socket#rooms 2012-12-18 18:02:28 -03:00
Guillermo Rauch
902373196e socket: added broadcast flag 2012-12-18 17:28:14 -03:00
Guillermo Rauch
ae516a3f06 test: added args + callback events tests 2012-12-18 17:27:22 -03:00
Guillermo Rauch
ecf937c775 test: style 2012-12-18 17:27:09 -03:00
Guillermo Rauch
d1def44858 test: added event ack tests 2012-12-18 17:23:53 -03:00
Guillermo Rauch
381bc4260a socket: forgot this js oddity that you can access objects with strings or numbers 2012-12-18 17:20:20 -03:00
Guillermo Rauch
8a5cb03fcb socket: fix Socket#ack 2012-12-18 17:20:01 -03:00
Guillermo Rauch
22c91d8e49 socket: allow for falsy packet.id 2012-12-18 17:19:36 -03:00
Guillermo Rauch
bd37a9a34b socket: protect against __proto__ deletion 2012-12-18 17:00:44 -03:00
Guillermo Rauch
2fa98fb61a package: bumped socket.io-parser 2012-12-18 15:50:14 -03:00
Guillermo Rauch
6b3cdd7c9c test: added test for event emitting with send 2012-12-18 15:25:56 -03:00
Guillermo Rauch
3038ce5526 test: added event emitting test 2012-12-18 15:24:24 -03:00
Guillermo Rauch
a0020bcb2c socket: fix event packet 2012-12-18 15:22:16 -03:00
Guillermo Rauch
c929f8c7fb test: added socket event reception test 2012-12-18 15:18:26 -03:00
Guillermo Rauch
1d8a747773 test: added socket#send test 2012-12-18 15:15:42 -03:00
Guillermo Rauch
56ed3fbe75 socket: fixed packet handling 2012-12-18 15:15:12 -03:00
Guillermo Rauch
169046e026 test: added disconncet(true) test 2012-12-18 14:58:09 -03:00
Guillermo Rauch
56221bc093 socket: attempt to send disconnect packets prior to closing the transport
this will prevent reconnection from triggering
2012-12-18 14:57:37 -03:00
Guillermo Rauch
5da04cd1a9 socket: fixed EventEmitter inheritance 2012-12-18 14:57:23 -03:00
Guillermo Rauch
342845d5c2 socket: added missing acks initialization 2012-12-18 14:56:58 -03:00
Guillermo Rauch
97b63b0860 namespace: blacklist newListener event 2012-12-18 14:56:44 -03:00
Guillermo Rauch
12d1dca7ca socket: added more blacklisted events 2012-12-18 14:56:24 -03:00
Guillermo Rauch
3a259d420c namespace: improve middleware logic 2012-12-18 14:55:58 -03:00
Guillermo Rauch
19837a0f86 client: added disconnect method 2012-12-18 14:55:42 -03:00
Guillermo Rauch
3feb98a346 client: removed extra line 2012-12-17 15:26:04 -03:00
Guillermo Rauch
a8ea0f4fb0 socket: added Emitter mixin 2012-12-17 14:36:24 -03:00
Guillermo Rauch
1609eaa4e5 index: added second parameter to of optional 2012-12-17 14:25:55 -03:00
Guillermo Rauch
e724e7bdf6 test: added test for of second parameter 2012-12-17 14:25:40 -03:00
Guillermo Rauch
06e7df4eb2 test: added multiplexing tests 2012-12-17 12:45:26 -03:00
Guillermo Rauch
28a19bfb43 test: added second parameter to helper to aid w testing namespaces 2012-12-17 12:45:13 -03:00
Guillermo Rauch
deefa7bbb9 client: style 2012-12-17 09:58:34 -03:00
Guillermo Rauch
bfd019c2f3 Readme: described Socket and Client classes 2012-12-17 09:36:11 -03:00
Guillermo Rauch
755cead37c Readme: document namespace events 2012-12-17 09:01:45 -03:00
Guillermo Rauch
01e73669f9 test: added connect namespace event test 2012-12-17 09:00:17 -03:00
Guillermo Rauch
5022b06242 Readme: added build status 2012-12-17 08:52:00 -03:00
Guillermo Rauch
3afe5e3032 test: added basic namespace tests 2012-12-17 08:43:03 -03:00
Guillermo Rauch
4315732220 index: added missing on method 2012-12-17 08:39:12 -03:00
Guillermo Rauch
fcd969b1be index: fix style 2012-12-17 08:39:02 -03:00
Guillermo Rauch
c67d2d5494 namespace: instrument add 2012-12-17 08:29:43 -03:00
Guillermo Rauch
4f0fce34f5 index: fix client url 2012-12-17 08:29:25 -03:00
Guillermo Rauch
31adf5e45e lib: fixed static server binding 2012-12-17 01:10:03 -03:00
Guillermo Rauch
3063241eba test: fixed test for engine.io attachment 2012-12-17 01:09:50 -03:00
Guillermo Rauch
3b65a9f011 index: feel static server attachment order 2012-12-17 00:46:54 -03:00
Guillermo Rauch
f1e2af3d91 test: added client creation helper 2012-12-17 00:18:39 -03:00
Guillermo Rauch
70ce641d85 namespace: fix run call 2012-12-16 23:50:46 -03:00
Guillermo Rauch
c87a530b08 index: remove client event 2012-12-16 23:50:39 -03:00
Guillermo Rauch
fc65ed630a index: override path with /socket.io 2012-12-16 21:36:04 -03:00
Guillermo Rauch
98c4bb6955 test: fixed style 2012-12-16 19:13:02 -03:00
Guillermo Rauch
6d0b1a5117 test: basic namespaces tests 2012-12-16 19:12:03 -03:00
Guillermo Rauch
cb806c0d4e test: attachment and client serving tests 2012-12-16 18:58:17 -03:00
Guillermo Rauch
eb029808f5 Readme: muuuch nice readme <3 2012-12-16 18:58:00 -03:00
Guillermo Rauch
2615aa45e7 index: add warning about passing a function to attach 2012-12-16 18:53:46 -03:00
Guillermo Rauch
f6370c1635 index: removed middleware attachment possibility 2012-12-16 18:50:42 -03:00
Guillermo Rauch
4ecbf2a46e index: fix event listener override 2012-12-16 18:37:57 -03:00
Guillermo Rauch
c3d5024496 index: fix port binding 2012-12-16 18:37:46 -03:00
Guillermo Rauch
9c2224cca0 index: api cleanup 2012-12-14 10:07:07 -03:00
Guillermo Rauch
c695065c7a dox 2012-12-14 10:06:52 -03:00
Guillermo Rauch
44da490467 index: renamed client to static for clarity 2012-12-14 09:27:55 -03:00
Guillermo Rauch
8901efd085 package: added supertest 2012-12-14 09:18:44 -03:00
Guillermo Rauch
1e68a83bd3 index: fix send implementation 2012-12-14 09:18:34 -03:00
Guillermo Rauch
4ea334899f package: added client dep and superagent 2012-12-13 16:39:10 -03:00
Guillermo Rauch
5f397464a9 client: added static files 2012-12-13 16:38:58 -03:00
Guillermo Rauch
373c66f1ee index: added client serving with send 2012-12-13 16:38:23 -03:00
Guillermo Rauch
bec38c2ce1 index: move this to engine.io 2012-12-13 12:20:56 -03:00
Guillermo Rauch
b6a4899689 initial 1.0 commit 2012-12-13 12:14:54 -03:00
Guillermo Rauch
3af1ad982c Merge branch 'master' of github.com:LearnBoost/socket.io 2012-12-13 10:54:19 -03:00
Guillermo Rauch
8daa71302d Merge tag '0.9.12'
Release 0.9.12

Conflicts:
	package.json
2012-12-13 08:48:05 -03:00
Guillermo Rauch
b2a8ed1421 Release 0.9.12 2012-12-13 08:19:16 -03:00
Guillermo Rauch
0d3313f536 manager: fix for latest node which is returning a clone with listeners [viirya] 2012-12-13 08:18:42 -03:00
Guillermo Rauch
fcd4f6acfc Merge pull request #1078 from stouset/master
Fix operator precedence bug
2012-12-11 09:42:23 -08:00
Guillermo Rauch
80036cc50f Merge pull request #1082 from shapeshed/master
Fix leaking message:id, disconnect:id
2012-11-27 20:45:46 -08:00
Guillermo Rauch
373eadf7e1 Merge pull request #1086 from sampsasaarela/master
Fixed bug in symbian anna
2012-11-20 02:06:01 -08:00
Sampsa Saarela
ef54570313 Changed content-type in response header from text/plain to application/javascript because some browsers force file download (eg. symbian anna) 2012-11-20 11:53:01 +02:00
George Ornbo
6256f569b3 fix leaking message:id, disconnect:id #1081 #1064 #862 2012-11-12 13:11:23 +00:00
Stephen Touset
cd4dee7257 Respect operator precedence 2012-11-09 17:49:40 -08:00
Guillermo Rauch
3b7224c7e0 Release 0.9.11 2012-11-02 08:03:15 -07:00
Guillermo Rauch
2030cf1432 package: move redis to optionalDependenices [3rd-Eden] 2012-11-02 08:01:24 -07:00
Guillermo Rauch
7537e2543f transports: removed headers that are set by node from htmlfile [stbuehler] 2012-11-01 17:52:51 -07:00
Guillermo Rauch
e00913aae0 transports: fixed xhr-polling 2012-11-01 17:51:59 -07:00
Guillermo Rauch
dbabf20faa transports: fix for Connection: close [stbuehler] (fixes #406) 2012-11-01 17:14:06 -07:00
Guillermo Rauch
4de65523d9 Merge pull request #1061 from shripadk/master
Fix: Remove socket session from child processes on disconnect
2012-10-27 18:24:33 -07:00
Shripad K
7cca186bb1 fix: remove socket session from child processes in cluster on disconnect 2012-10-28 05:45:21 +05:30
Guillermo Rauch
ec07fa8308 Merge pull request #1031 from secobarbital/master
Fixed global variable leak
2012-09-15 13:46:03 -07:00
Seggy Umboh
f5c32c1490 Fixed global leak 2012-09-14 18:48:49 -07:00
Guillermo Rauch
c3ba8a722b Merge pull request #1008 from faeldt/master
Increase performance of generateId by avoiding sync calls to crypto.randomBytes
2012-09-10 15:06:40 -07:00
Guillermo Rauch
70b328f844 Merge pull request #1026 from jmatthewsr-ms/master
Websocket: Accept a PONG
2012-09-08 21:05:00 -07:00
Justin Matthews
32a44a3b5d Websocket: accept a pong (IE10 sends them) 2012-09-08 20:08:37 -07:00
Guillermo Rauch
c23ddb2bff Merge pull request #1022 from 3rd-Eden/master
Move redis
2012-09-07 13:38:36 -07:00
3rd-Eden
f7f219d6dd Move redis to the devDependencies, don't depend on redis as it's not a core component
to run Socket.IO.
2012-09-07 15:32:09 +02:00
Kristian Faeldt
f7d40d5f7b Moved generateId into an external module 2012-09-07 19:48:21 +09:00
Kristian Faeldt
da91c89147 Only fall back when no bytes available, not when threshold is reached 2012-08-28 19:15:55 +09:00
Kristian Faeldt
a10e963858 Added getRandomBytes to improve generateId performance 2012-08-28 18:56:11 +09:00
Guillermo Rauch
21a3733dec Merge pull request #1001 from crazyrobot/patch-1
Redis Store: removed unneeded module ('assert')
2012-08-22 16:28:28 -07:00
Itai
4a6890898a Redis Store: removed unneeded module ('assert')
It's not used anywhere in the file and the test file (test/stores.redis.test.js) uses the 'should' module.
I'm assuming this is a leftover.
2012-08-23 02:27:03 +03:00
Guillermo Rauch
ab2a0b6a8b test: removed protocolVersion private api from tests 2012-08-13 16:14:28 -07:00
Guillermo Rauch
c797d2a9fb *: added ws dependency 2012-08-13 16:14:15 -07:00
Guillermo Rauch
d558c97089 transport: rewrite websocket transport to use ws client 2012-08-13 16:14:03 -07:00
Guillermo Rauch
b483dfcce9 test: removed old transports tests 2012-08-13 16:13:51 -07:00
Guillermo Rauch
f59e8aceaa manager: implemented ws 2012-08-13 16:13:38 -07:00
Guillermo Rauch
de9e8dffe1 Release 0.9.10 2012-08-10 13:34:50 -07:00
Guillermo Rauch
3a3044ebba Merge pull request #972 from Coreh/express-3.x-readme
Add express 3.0 instructions on Readme.md
2012-08-10 10:17:55 -07:00
Guillermo Rauch
d10b4dd1bd Merge pull request #985 from GICodeWarrior/log-case-fix
Don't lowercase log messages
2012-08-08 18:03:57 -07:00
Rusty Burchfield
12beee2d63 Don't lowercase log messages
Lowercasing log messages is unnecessary.  It makes some messages difficult to
read, and others difficult to search for.
2012-08-08 11:32:57 -07:00
Guillermo Rauch
875f14d16b Revert "Fix infinite recursion in Websocket parsers."
This reverts commit c218468f67.
2012-08-07 13:18:41 -07:00
Guillermo Rauch
8ca8990a0c Merge pull request #983 from GICodeWarrior/parser-recursion
Fix infinite recursion in Websocket parsers.
2012-08-06 13:16:37 -07:00
Rusty Burchfield
c218468f67 Fix infinite recursion in Websocket parsers.
If a client is feeding messages faster than server can handle them, infinite
recursion occurs.  Basically, the "overflow" data gets added to the parser and
it immediately parses a new message.

The fix pushes the processing of the next message (in this edge case) onto the
event queue.  This prevents the stack from recursing indefinitely.  This also
prevents a fast client from starving other clients.
2012-08-06 13:03:51 -07:00
Guillermo Rauch
4164e3bd7e Merge pull request #981 from doozr/honour-flash-settings
Honour flash settings
2012-08-06 08:59:17 -07:00
Guillermo Rauch
46227e7ac9 Merge pull request #980 from doozr/jsonp-error-crash
Always set the HTTP response in case an error should be returned to the client
2012-08-06 08:58:57 -07:00
Craig Andrews
d723d363b2 Always set the HTTP response in case an error should be returned to the client 2012-08-06 14:16:06 +01:00
Craig Andrews
fa1c1b2ada Create or destroy the flash policy server on configuration change 2012-08-06 14:14:15 +01:00
Craig Andrews
d32a848c3f Honour configuration to disable flash policy server 2012-08-06 14:14:14 +01:00
Guillermo Rauch
48ad0d3d1d Release 0.9.9 2012-08-01 15:14:02 -07:00
Guillermo Rauch
281a467960 manager: added response to sync disconnect xhrs 2012-08-01 15:08:06 -07:00
Guillermo Rauch
1fa74a46a3 Revert "Fix disconnectSync getting ignored"
This reverts commit f48b40e134.
2012-08-01 11:58:28 -07:00
Guillermo Rauch
ca4e3f32a3 Merge pull request #975 from huancz/master
fix issue #961 - restore compatibility with earlier node releases (up to 0.4.x)
2012-07-31 08:34:22 -07:00
Guillermo Rauch
9dd8134e6a Merge pull request #970 from renier/master
Codebase needs a license file (#965)
2012-07-31 08:32:07 -07:00
Renier Morales
180f1c91b9 Put license text in its own file (#965) 2012-07-31 11:07:21 -04:00
Marco Aurélio
bddf652c25 Add express 3.0 instructions on Readme.md 2012-07-30 15:53:47 -03:00
Guillermo Rauch
c795e4cf1a Merge pull request #971 from Coreh/express-3.x-warn
Add warning to .listen() to ease the migration to Express 3.x
2012-07-30 11:49:53 -07:00
Marco Aurélio
6afbb34581 Add warning to .listen() to ease the migration to Express 3.x 2012-07-30 15:43:00 -03:00
Guillermo Rauch
ac39dbc721 Merge pull request #964 from crickeys/xhr_polling_disconnectSync
Fix disconnectSync getting ignored
2012-07-27 10:06:03 -07:00
Petr Běhan
a5c5c20438 restore compatibility with node 0.4.x 2012-07-27 15:38:57 +02:00
Brian Gruber
f48b40e134 Fix disconnectSync getting ignored
If using xhr-polling and a browser closes a tab or window, the
disconnectSync in the socket.io-client method is called which sends an
XHR request to the server indicating a disconnect. This line would cause
that to be ignored and so the server would have to wait for a timeout to
mark them as disconnect. This was possibly because it was sent from a
different tcp socket than the current connection.
2012-07-26 21:19:00 -05:00
Guillermo Rauch
1679fd564c Release 0.9.8 2012-07-24 17:36:30 -07:00
Guillermo Rauch
bb900d445a Release 0.9.7 2012-07-24 11:16:20 -07:00
Guillermo Rauch
c6fed55f53 tests: fixed tests for 0.8 2012-07-24 10:39:23 -07:00
Guillermo Rauch
6adebc85fc Merge pull request #958 from xaroth8088/master
Prevent crash when socket leaves a room twice.
2012-07-22 11:26:21 -07:00
xaroth8088
7a087bcc94 Prevent crash when socket leaves a room twice. 2012-07-22 11:09:06 -07:00
Guillermo Rauch
18422183c8 Merge pull request #957 from xaroth8088/master
Corrects unsafe usage of for..in, permitting socket.io to be used in environments that extend Object, etc.
2012-07-21 11:44:28 -07:00
xaroth8088
aeb904f58b Corrects unsafe usage of for..in, permitting socket.io to be used in environments where Object, Function, etc. have been extended.
http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
2012-07-21 11:30:15 -07:00
xaroth8088
9c0b9de7f0 Revert "Corrects unsafe usage of for..in, permitting socket.io to be used in environments that extend Object, etc."
This reverts commit 81552c11ca.
2012-07-21 11:21:11 -07:00
xaroth8088
81552c11ca Corrects unsafe usage of for..in, permitting socket.io to be used in environments that extend Object, etc.
http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
2012-07-21 10:29:20 -07:00
Guillermo Rauch
e1fe76aebe Fix for node 0.8 with gzip compression. Thanks @vadimi 2012-07-09 16:58:02 -07:00
Guillermo Rauch
8197a0c854 Merge pull request #929 from sjonnet19/patch-1
Update redis to support Node 0.8.x
2012-06-26 06:29:08 -07:00
Shawn Jonnet
2b91f1407f Update redis to support Node 0.8.x 2012-06-25 23:30:24 -03:00
Guillermo Rauch
3b9715e8e7 Merge pull request #869 from MrSwitch/master
Small change to demo copy
2012-05-03 06:24:15 -07:00
Andrew Dodson
4e13cfb03e Update copy 2012-05-03 12:16:01 +10:00
Guillermo Rauch
39671e81a5 Merge pull request #868 from bodash/patch-1
I continued to have websocket connection issues in Safari when using SSL...
2012-05-02 12:21:24 -07:00
bodash
ffa8994a23 I continued to have websocket connection issues in Safari when using SSL that terminated at a load balancer. The shorthand logic that was here was nice and compact but didn't seem to work. Took the "intent" of the short hand and made it a bit more verbose and now it works. 2012-05-02 13:18:46 -06:00
Guillermo Rauch
de1afe1317 Merge pull request #857 from martinthomson/bug/856
Fix for ID generation vulnerability #856
2012-04-26 15:49:24 -07:00
Martin Thomson
aaad106b90 Adding node 0.4 backward compat for id gen 2012-04-26 15:08:19 -07:00
Martin Thomson
f850ddccd0 Removing more fixes for other bug 2012-04-26 14:35:17 -07:00
Martin Thomson
8d269aae4c Removing fixes for other bug 2012-04-26 14:33:37 -07:00
Martin Thomson
67b4eb9abd Making ID generation securely random 2012-04-26 14:28:00 -07:00
Guillermo Rauch
fe6dd87443 Merge pull request #848 from mbrevoort/redisStoreRaceCondition
Fix Redis Store race condition in manager onOpen unsubscribe callback
2012-04-23 15:30:30 -07:00
Mike Brevoort
d9aeaa494f Fix Redis Store race condition in manager onOpen unsubscribe callback 2012-04-23 16:06:31 -06:00
Guillermo Rauch
2024d45383 Merge pull request #841 from TooTallNate/master
fix for EventEmitters always reusing the same Array instance for listeners
2012-04-19 13:30:13 -07:00
Nathan Rajlich
e1884859bc fix for EventEmitters always reusing the same Array instance for listeners
This fixes node v0.7.x.

The node commits that broke this old behavior is here:
  78dc13fbf9%5E...928ea564d16da47e615ddac627e0b4d4a40d8196
2012-04-19 13:18:22 -07:00
Guillermo Rauch
0242a2ddf3 Merge branch 'master' of github.com:LearnBoost/socket.io 2012-04-17 19:51:49 -03:00
Guillermo Rauch
dbe6d5f740 Release 0.9.6 2012-04-17 19:51:37 -03:00
Guillermo Rauch
e98fc7bc86 Fixed XSS in jsonp-polling. 2012-04-17 19:48:32 -03:00
Guillermo Rauch
9bbf17f31e Merge pull request #827 from crickeys/patch-4
Fixes when browser doesn't send origin header, defaults to empty string ...
2012-04-11 15:02:50 -07:00
crickeys
1a5a87af13 Fixes when browser doesn't send origin header, defaults to empty string instead of UNDEFINED (which would throw an error on the origin.match(/^https/) below 2012-04-11 14:41:07 -05:00
156 changed files with 182826 additions and 17916 deletions

26
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,26 @@
*Note*: for support questions, please use one of these channels: [stackoverflow](http://stackoverflow.com/questions/tagged/socket.io) or [slack](https://socketio.slack.com)
### You want to:
* [x] report a *bug*
* [ ] request a *feature*
### Current behaviour
### Steps to reproduce (if the current behaviour is a bug)
**Note**: the best way to get a quick answer is to provide a failing test case, by forking the following [fiddle](https://github.com/darrachequesne/socket.io-fiddle) for example.
### Expected behaviour
### Setup
- OS:
- browser:
- socket.io version:
### Other information (e.g. stacktraces, related issues, suggestions how to fix)

18
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,18 @@
### The kind of change this PR does introduce
* [x] a bug fix
* [ ] a new feature
* [ ] an update to the documentation
* [ ] a code change that improves performance
* [ ] other
### Current behaviour
### New behaviour
### Other information (e.g. related issues)

3
.gitignore vendored
View File

@@ -8,3 +8,6 @@ lib-cov
*.pid
benchmarks/*.png
node_modules
coverage
.idea
dist

View File

@@ -1,3 +0,0 @@
support
test
examples

View File

@@ -1,6 +1,12 @@
sudo: false
language: node_js
node_js:
- 0.6
- "4"
- "6"
- "7"
git:
depth: 1
notifications:
irc: "irc.freenode.org#socket.io"

View File

@@ -1,4 +1,461 @@
2.0.2 / 2017-06-01
===================
* [fix] Fix timing issues with middleware (#2948)
2.0.1 / 2017-05-09
===================
* [fix] Update path of client file (#2934)
2.0.0 / 2017-05-09
===================
* [feat] Move binary detection to the parser (#2923)
* [feat] Allow to join several rooms at once (#2879)
* [feat] Merge Engine.IO and Socket.IO handshake packets (#2833)
* [feat] Allow the use of custom parsers (#2829)
* [fix] Use path.resolve by default and require.resolve as a fallback (#2797)
* [fix] Properly close the connection on error (#2681)
* [fix] Prevent null from being accepted as argument (#2606)
* [perf] Use shared instance of the encoder (#2825)
* [perf] Reset properties instead of deleting them (#2826)
* [perf] micro-optimisations (#2793)
* [chore] Merge history of 1.7.x and 0.9.x branches (#2930)
* [chore] Added backers and sponsors on the README (#2933)
* [chore] Bump dependencies (#2926)
* [chore] Bump socket.io-adapter to version 1.0.0 (#2867)
* [chore] Bump engine.io to version 2.0.2 (#2864)
* [chore] Bump engine.io to version 2.0.0 (#2832)
* [chore] Update issue template with fiddle (#2811)
* [chore] Update copyright year LICENSE to 2017 (#2803)
* [docs] Add an example of custom parser (#2929)
* [docs] Replace non-breaking space with proper whitespace (#2913)
* [docs] Update emit cheatsheet (#2906)
* [docs] Explicitly document that Server extends EventEmitter (#2874)
* [docs] Add server.engine.generateId attribute (#2880)
* [docs] Fix wrong space character in README (#2900)
* [docs] Fix documentation for 'connect' event (#2898)
* [docs] Add webpack build example (#2828)
* [docs] Update the wording to match the code example (#2853)
* [docs] Small addition to the Express Readme Part (#2846)
* [docs] Add a 'Features' section in the README (#2824)
* [docs] Add httpd cluster example (#2819)
* [docs] Add haproxy cluster example (#2818)
* [docs] Add nginx cluster example (#2817)
* [docs] Implement whiteboard example (#2810)
* [docs] Fix documentation for `local` flag (#2816)
* [docs] Add emit cheatsheet (#2815)
* [docs] Add pingInterval/pingTimeout/transports options in the API documentation (#2814)
* [docs] Add an example for socket.join() method (#2813)
* [docs] Fix a typo on `clients` method in the API documentation (#2812)
* [docs] Fix wrong argument name in API.md (#2802)
* [docs] Add install script on Readme.md (#2780)
* [docs] API documentation (#2784)
1.7.4 / 2017-05-07
===================
* [chore] Bump engine.io to version 1.8.4
0.9.18 / 2017-05-07
===================
* Remove process.EventEmitter usage for Node 7.x
1.7.3 / 2017-02-17
===================
* [chore] Bump engine.io to version 1.8.3
1.7.2 / 2016-12-11
===================
* [chore] Bump engine.io to version 1.8.2 (#2782)
* [fix] Fixes socket.use error packet (#2772)
1.7.1 / 2016-11-28
===================
1.7.0 / 2016-11-27
===================
* [docs] Comment connected socket availability for adapters (#2081)
* [docs] Fixed grammar issues in the README.md (#2159)
* [feature] serve sourcemap for socket.io-client (#2482)
* [feature] Add a `local` flag (#2628)
* [chore] Bump engine.io to version 1.8.1 (#2765)
* [chore] Update client location and serve minified file (#2766)
1.6.0 / 2016-11-20
==================
* [fix] Make ETag header comply with standard. (#2603)
* [feature] Loading client script on demand. (#2567)
* [test] Fix leaking clientSocket (#2721)
* [feature] Add support for all event emitter methods (#2601)
* [chore] Update year to 2016 (#2456)
* [feature] Add support for socket middleware (#2306)
* [feature] add support for Server#close(callback) (#2748)
* [fix] Don't drop query variables on handshake (#2745)
* [example] Add disconnection/reconnection logs to the chat example (#2675)
* [perf] Minor code optimizations (#2219)
* [chore] Bump debug to version 2.3.3 (#2754)
* [chore] Bump engine.io to version 1.8.0 (#2755)
* [chore] Bump socket.io-adapter to version 0.5.0 (#2756)
1.5.1 / 2016-10-24
==================
* [fix] Avoid swallowing exceptions thrown by user event handlers (#2682)
* [test] Use client function to unify `client` in test script (#2731)
* [docs] Add link to LICENSE (#2221)
* [docs] Fix JSDoc of optional parameters (#2465)
* [docs] Fix typo (#2724)
* [docs] Link readme npm package badge to npm registry page (#2612)
* [docs] Minor fixes (#2526)
* [chore] Bump socket.io-parser to 2.3.0 (#2730)
* [chore] Add Github issue and PR templates (#2733)
* [chore] Bump engine.io to 1.7.2 (#2729)
* [chore] Bump socket.io-parser to 2.3.1 (#2734)
1.5.0 / 2016-10-06
==================
* [feature] stop append /# before id when no namespace (#2508)
* [feature] Add a 'disconnecting' event to access to socket.rooms upon disconnection (#2332)
* [fix] Fix query string management (#2422)
* [fix] add quote to exec paths, prevent error when spaces in path (#2508)
* [docs] Prevent mixup for new programmers (#2599)
* [example] Fix chat display in Firefox (#2477)
* [chore] Add gulp & babel in the build process (#2471)
* [chore] Bump engine.io to 1.7.0 (#2707)
* [chore] Remove unused zuul-ngrok dependency (#2708)
* [chore] Point towards current master of socket.io-client (#2710)
* [chore] Restrict files included in npm package (#2709)
* [chore] Link build badge to master branch (#2549)
1.4.8 / 2016-06-23
==================
* package: bump `engine.io`
1.4.7 / 2016-06-23
==================
* package: bump `engine.io`
1.4.6 / 2016-05-02
==================
* package: bump engine.io
1.4.5 / 2016-01-26
==================
* fix closing the underlying `http.Server`
1.4.4 / 2016-01-10
==================
* package: bump `engine.io`
1.4.3 / 2016-01-08
==================
* bump `socket.io-client`
1.4.2 / 2016-01-07
==================
* bump `engine.io`
1.4.1 / 2016-01-07
==================
* version bump
1.4.0 / 2015-11-28
==================
* socket.io: increase large binary data test timeout
* package: bump `engine.io` for release
* trigger callback even when joining an already joined room
* package: bump parser
* namespace: clear rooms flag after a clients call (fixes #1978)
* package: bump `socket.io-parser`
* fixed tests with large data
* fixed a typo in the example code
* package: bump mocha
* package: bump `has-binary` and `zuul-ngrok`
* package: bump `engine.io` and `socket.io-client`
* README: clarified documentation of Socket.in
* README: fixed up legacy repo links
* test: better timeout for stress test
* socket: don't set request property which has a getter
* removed proxy index file
* support flags on namespace
* improve Socket#packet and Client#packet
* socket: warn node_redis-style about missing `error`
* test: added failing test
* test: increase timeout for large binary data test
* package: bump `has-binary` to work with all objects (fixes #1955)
* fix origin verification default https port [evanlucas]
* support compression [nkzawa]
* changed type of `Client#sockets`, `Namespace#sockets` and `Socket#rooms` to maps (instead of arrays)
1.3.7 / 2015-09-21
==================
* package: bump `socket.io-client` for node4 compatibility
* package: bump `engine.io` for node4 compatibility
1.3.6 / 2015-07-14
==================
* package: bump `engine.io` to fix build on windows
1.3.5 / 2015-03-03
==================
* package: bump `socket.io-parser`
1.3.4 / 2015-02-14
==================
* package: bump `socket.io-client`
1.3.3 / 2015-02-03
==================
* socket: warn node_redis-style about missing `error`
* package: bump parser to better handle bad binary packets
1.3.2 / 2015-01-19
==================
* no change on this release
1.3.1 / 2015-01-19
==================
* no change on this release
* package: bump `engine.io`
1.3.0 / 2015-01-19
==================
* package: bump `engine.io`
* add test for reconnection after server restarts [rase-]
* update license with up-to-date year range [fay-jai]
* fix leaving unknown rooms [defunctzombie]
* allow null origins when allowed origins is a function [drewblaisdell]
* fix tests on node 0.11
* package: fix `npm test` to run on windows
* package: bump `debug` v2.1.0 [coderaiser]
* added tests for volatile [rase-]
1.2.1 / 2014-11-21
==================
* fix protocol violations and improve error handling (GH-1880)
* package: bump `engine.io` for websocket leak fix [3rd-Eden]
* style tweaks
1.2.0 / 2014-10-27
==================
* package: bump `engine.io`
* downloads badge
* add test to check that empty rooms are autopruned
* added Server#origins(v:Function) description for dynamic CORS
* added test coverage for Server#origins(function) for dynamic CORS
* added optional Server#origins(function) for dynamic CORS
* fix usage example for Server#close
* package: fix main file for example application 'chat'
* package: bump `socket.io-parser`
* update README http ctor to createServer()
* bump adapter with a lot of fixes for room bookkeeping
1.1.0 / 2014-09-04
==================
* examples: minor fix of escaping
* testing for equivalence of namespaces starting with / or without
* update index.js
* added relevant tests
* take "" and "/" as equivalent namespaces on server
* use svg instead of png to get better image quality in readme
* make CI build faster
* fix splice arguments and `socket.rooms` value update in `socket.leaveAll`.
* client cannot connect to non-existing namespaces
* bump engine.io version to get the cached IP address
* fixed handshake object address property and made the test case more strict.
* package: bump `engine.io`
* fixed the failing test where server crashes on disconnect involving connectBuffer
* npmignore: ignore `.gitignore` (fixes #1607)
* test: added failing case for `socket.disconnect` and nsps
* fix repo in package.json
* improve Close documentation
* use ephemeral ports
* fix: We should use the standard http protocol to handler the etag header.
* override default browser font-family for inputs
* update has-binary-data to 1.0.3
* add close specs
* add ability to stop the http server even if not created inside socket.io
* make sure server gets close
* Add test case for checking that reconnect_failed is fired only once upon failure
* package: bump `socket.io-parser` for `component-emitter` dep fix
1.0.6 / 2014-06-19
==================
* package: bump `socket.io-client`
1.0.5 / 2014-06-16
==================
* package: bump `engine.io` to fix jsonp `\n` bug and CORS warnings
* index: fix typo [yanatan16]
* add `removeListener` to blacklisted events
* examples: clearer instructions to install chat example
* index: fix namespace `connectBuffer` issue
1.0.4 / 2014-06-02
==================
* package: bump socket.io-client
1.0.3 / 2014-05-31
==================
* package: bump `socket.io-client`
* package: bump `socket.io-parser` for binary ACK fix
* package: bump `engine.io` for binary UTF8 fix
* example: fix XSS in chat example
1.0.2 / 2014-05-28
==================
* package: bump `socket.io-parser` for windows fix
1.0.1 / 2014-05-28
==================
* bump due to bad npm tag
1.0.0 / 2014-05-28
==================
* stable release
1.0.0-pre5 / 2014-05-22
=======================
* package: bump `socket.io-client` for parser fixes
* package: bump `engine.io`
1.0.0-pre4 / 2014-05-19
=======================
* package: bump client
1.0.0-pre3 / 2014-05-17
=======================
* package: bump parser
* package: bump engine.io
1.0.0-pre2 / 2014-04-27
=======================
* package: bump `engine.io`
* added backwards compatible of engine.io maxHttpBufferSize
* added test that server and client using same protocol
* added support for setting allowed origins
* added information about logging
* the set function in server can be used to set some attributes for BC
* fix error in callback call 'done' instead of 'next' in docs
* package: bump `socket.io-parser`
* package: bump `expect.js`
* added some new tests, including binary with acks
1.0.0-pre / 2014-03-14
======================
* implemented `engine.io`
* implemented `socket.io-adapter`
* implemented `socket.io-protocol`
* implemented `debug` and improved instrumentation
* added binary support
* added new `require('io')(srv)` signature
* simplified `socket.io-client` serving
0.9.14 / 2013-03-29
===================
* manager: fix memory leak with SSL [jpallen]
0.9.13 / 2012-12-13
===================
* package: fixed `base64id` requirement
0.9.12 / 2012-12-13
===================
* manager: fix for latest node which is returning a clone with `listeners` [viirya]
0.9.11 / 2012-11-02
===================
* package: move redis to optionalDependenices [3rd-Eden]
* bumped client
0.9.10 / 2012-08-10
===================
* Don't lowercase log messages
* Always set the HTTP response in case an error should be returned to the client
* Create or destroy the flash policy server on configuration change
* Honour configuration to disable flash policy server
* Add express 3.0 instructions on Readme.md
* Bump client
0.9.9 / 2012-08-01
==================
* Fixed sync disconnect xhrs handling
* Put license text in its own file (#965)
* Add warning to .listen() to ease the migration to Express 3.x
* Restored compatibility with node 0.4.x
0.9.8 / 2012-07-24
==================
* Bumped client.
0.9.7 / 2012-07-24
==================
* Prevent crash when socket leaves a room twice.
* Corrects unsafe usage of for..in
* Fix for node 0.8 with `gzip compression` [vadimi]
* Update redis to support Node 0.8.x
* Made ID generation securely random
* Fix Redis Store race condition in manager onOpen unsubscribe callback
* Fix for EventEmitters always reusing the same Array instance for listeners
0.9.6 / 2012-04-17
==================
* Fixed XSS in jsonp-polling.
0.9.5 / 2012-04-05
==================

22
LICENSE Normal file
View File

@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2014-2017 Automattic <dev@cloudup.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
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.

View File

@@ -1,31 +1,8 @@
ALL_TESTS = $(shell find test/ -name '*.test.js')
ALL_BENCH = $(shell find benchmarks -name '*.bench.js')
run-tests:
@./node_modules/.bin/expresso \
-t 3000 \
-I support \
--serial \
$(TESTFLAGS) \
$(TESTS)
test:
@$(MAKE) NODE_PATH=lib TESTS="$(ALL_TESTS)" run-tests
@./node_modules/.bin/gulp test
test-cov:
@TESTFLAGS=--cov $(MAKE) test
@./node_modules/.bin/gulp test-cov
test-leaks:
@ls test/leaks/* | xargs node --expose_debug_as=debug --expose_gc
run-bench:
@node $(PROFILEFLAGS) benchmarks/runner.js
bench:
@$(MAKE) BENCHMARKS="$(ALL_BENCH)" run-bench
profile:
@PROFILEFLAGS='--prof --trace-opt --trace-bailout --trace-deopt' $(MAKE) bench
.PHONY: test bench profile
.PHONY: test

491
Readme.md
View File

@@ -1,345 +1,242 @@
# Socket.IO
Socket.IO is a Node.JS project that makes WebSockets and realtime possible in
all browsers. It also enhances WebSockets by providing built-in multiplexing,
horizontal scalability, automatic JSON encoding/decoding, and more.
# socket.io
## How to Install
[![Backers on Open Collective](https://opencollective.com/socketio/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/socketio/sponsors/badge.svg)](#sponsors)
[![Build Status](https://secure.travis-ci.org/socketio/socket.io.svg?branch=master)](https://travis-ci.org/socketio/socket.io)
[![Dependency Status](https://david-dm.org/socketio/socket.io.svg)](https://david-dm.org/socketio/socket.io)
[![devDependency Status](https://david-dm.org/socketio/socket.io/dev-status.svg)](https://david-dm.org/socketio/socket.io#info=devDependencies)
[![NPM version](https://badge.fury.io/js/socket.io.svg)](https://www.npmjs.com/package/socket.io)
![Downloads](https://img.shields.io/npm/dm/socket.io.svg?style=flat)
[![](http://slack.socket.io/badge.svg?)](http://slack.socket.io)
## Features
Socket.IO enables real-time bidirectional event-based communication. It consists in:
- a Node.js server (this repository)
- a [Javascript client library](https://github.com/socketio/socket.io-client) for the browser (or a Node.js client)
Some implementations in other languages are also available:
- [Java](https://github.com/socketio/socket.io-client-java)
- [C++](https://github.com/socketio/socket.io-client-cpp)
- [Swift](https://github.com/socketio/socket.io-client-swift)
Its main features are:
#### Reliability
Connections are established even in the presence of:
- proxies and load balancers.
- personal firewall and antivirus software.
For this purpose, it relies on [Engine.IO](https://github.com/socketio/engine.io), which first establishes a long-polling connection, then tries to upgrade to better transports that are "tested" on the side, like WebSocket. Please see the [Goals](https://github.com/socketio/engine.io#goals) section for more information.
#### Auto-reconnection support
Unless instructed otherwise a disconnected client will try to reconnect forever, until the server is available again. Please see the available reconnection options [here](https://github.com/socketio/socket.io-client/blob/master/docs/API.md#new-managerurl-options).
#### Disconnection detection
An heartbeat mechanism is implemented at the Engine.IO level, allowing both the server and the client to know when the other one is not responding anymore.
That functionality is achieved with timers set on both the server and the client, with timeout values (the `pingInterval` and `pingTimeout` parameters) shared during the connection handshake. Those timers require any subsequent client calls to be directed to the same server, hence the `sticky-session` requirement when using multiples nodes.
#### Binary support
Any serializable data structures can be emitted, including:
- [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) and [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) in the browser
- [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) and [Buffer](https://nodejs.org/api/buffer.html) in Node.js
#### Simple and convenient API
Sample code:
```js
io.on('connection', function(socket){
socket.emit('request', /* */); // emit an event to the socket
io.emit('broadcast', /* */); // emit an event to all connected sockets
socket.on('reply', function(){ /* */ }); // listen to the event
});
```
#### Cross-browser
Browser support is tested in Saucelabs:
[![Sauce Test Status](https://saucelabs.com/browser-matrix/socket.svg)](https://saucelabs.com/u/socket)
#### Multiplexing support
In order to create separation of concerns within your application (for example per module, or based on permissions), Socket.IO allows you to create several `Namespaces`, which will act as separate communication channels but will share the same underlying connection.
#### Room support
Within each `Namespace`, you can define arbitrary channels, called `Rooms`, that sockets can join and leave. You can then broadcast to any given room, reaching every socket that has joined it.
This is a useful feature to send notifications to a group of users, or to a given user connected on several devices for example.
**Note:** Socket.IO is not a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the ack id when a message acknowledgement is needed. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a WebSocket server (like `ws://echo.websocket.org`) either. Please see the protocol specification [here](https://github.com/socketio/socket.io-protocol).
## Installation
```bash
npm install socket.io
npm install socket.io --save
```
## How to use
First, require `socket.io`:
The following example attaches socket.io to a plain Node.JS
HTTP server listening on port `3000`.
```js
var io = require('socket.io');
```
Next, attach it to a HTTP/HTTPS server. If you're using the fantastic `express`
web framework:
```js
var app = express.createServer()
, io = io.listen(app);
app.listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
var server = require('http').createServer();
var io = require('socket.io')(server);
io.on('connection', function(client){
client.on('event', function(data){});
client.on('disconnect', function(){});
});
server.listen(3000);
```
Finally, load it from the client side code:
```html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
```
For more thorough examples, look at the `examples/` directory.
## Short recipes
### Sending and receiving events.
Socket.IO allows you to emit and receive custom events.
Besides `connect`, `message` and `disconnect`, you can emit custom events:
### Standalone
```js
// note, io.listen(<port>) will create a http server for you
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
io.sockets.emit('this', { will: 'be received by everyone' });
socket.on('private message', function (from, msg) {
console.log('I received a private message by ', from, ' saying ', msg);
});
socket.on('disconnect', function () {
io.sockets.emit('user disconnected');
});
});
var io = require('socket.io')();
io.on('connection', function(client){});
io.listen(3000);
```
### Storing data associated to a client
### In conjunction with Express
Sometimes it's necessary to store data associated with a client that's
necessary for the duration of the session.
#### Server side
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. Also make sure to call `.listen` on the `server`, not the `app`.
```js
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on('set nickname', function (name) {
socket.set('nickname', name, function () { socket.emit('ready'); });
});
socket.on('msg', function () {
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
});
});
});
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(){ /* … */ });
server.listen(3000);
```
#### Client side
### In conjunction with Koa
```html
<script>
var socket = io.connect('http://localhost');
socket.on('connect', function () {
socket.emit('set nickname', confirm('What is your nickname?'));
socket.on('ready', function () {
console.log('Connected !');
socket.emit('msg', confirm('What is your message?'));
});
});
</script>
```
### Restricting yourself to a namespace
If you have control over all the messages and events emitted for a particular
application, using the default `/` namespace works.
If you want to leverage 3rd-party code, or produce code to share with others,
socket.io provides a way of namespacing a `socket`.
This has the benefit of `multiplexing` a single connection. Instead of
socket.io using two `WebSocket` connections, it'll use one.
The following example defines a socket that listens on '/chat' and one for
'/news':
#### Server side
Like Express.JS, Koa works by exposing an application as a request
handler function, but only by calling the `callback` method.
```js
var io = require('socket.io').listen(80);
var chat = io
.of('/chat')
.on('connection', function (socket) {
socket.emit('a message', { that: 'only', '/chat': 'will get' });
chat.emit('a message', { everyone: 'in', '/chat': 'will get' });
});
var news = io
.of('/news');
.on('connection', function (socket) {
socket.emit('item', { news: 'item' });
});
var app = require('koa')();
var server = require('http').createServer(app.callback());
var io = require('socket.io')(server);
io.on('connection', function(){ /* … */ });
server.listen(3000);
```
#### Client side:
## Documentation
```html
<script>
var chat = io.connect('http://localhost/chat')
, news = io.connect('http://localhost/news');
Please see the documentation [here](/docs/README.md). Contributions are welcome!
chat.on('connect', function () {
chat.emit('hi!');
});
## Debug / logging
news.on('news', function () {
news.emit('woot');
});
</script>
Socket.IO is powered by [debug](https://github.com/visionmedia/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
```
### Sending volatile messages.
## Testing
Sometimes certain messages can be dropped. Let's say you have an app that
shows realtime tweets for the keyword `bieber`.
If a certain client is not ready to receive messages (because of network slowness
or other issues, or because he's connected through long polling and is in the
middle of a request-response cycle), if he doesn't receive ALL the tweets related
to bieber your application won't suffer.
In that case, you might want to send those messages as volatile messages.
#### Server side
```js
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
var tweets = setInterval(function () {
getBieberTweet(function (tweet) {
socket.volatile.emit('bieber tweet', tweet);
});
}, 100);
socket.on('disconnect', function () {
clearInterval(tweets);
});
});
```
#### Client side
In the client side, messages are received the same way whether they're volatile
or not.
### Getting acknowledgements
Sometimes, you might want to get a callback when the client confirmed the message
reception.
To do this, simply pass a function as the last parameter of `.send` or `.emit`.
What's more, when you use `.emit`, the acknowledgement is done by you, which
means you can also pass data along:
#### Server side
```js
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on('ferret', function (name, fn) {
fn('woot');
});
});
npm test
```
This runs the `gulp` task `test`. By default the test will be run with the source code in `lib` directory.
#### Client side
Set the environmental variable `TEST_VERSION` to `compat` to test the transpiled es5-compat version of the code.
```html
<script>
var socket = io.connect(); // TIP: .connect with no args does auto-discovery
socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too!
socket.emit('ferret', 'tobi', function (data) {
console.log(data); // data will be 'woot'
});
});
</script>
```
The `gulp` task `test` will always transpile the source code into es5 and export to `dist` first before running the test.
### Broadcasting messages
To broadcast, simply add a `broadcast` flag to `emit` and `send` method calls.
Broadcasting means sending a message to everyone else except for the socket
that starts it.
## Backers
#### Server side
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/socketio#backer)]
```js
var io = require('socket.io').listen(80);
<a href="https://opencollective.com/socketio/backer/0/website" target="_blank"><img src="https://opencollective.com/socketio/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/1/website" target="_blank"><img src="https://opencollective.com/socketio/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/2/website" target="_blank"><img src="https://opencollective.com/socketio/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/3/website" target="_blank"><img src="https://opencollective.com/socketio/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/4/website" target="_blank"><img src="https://opencollective.com/socketio/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/5/website" target="_blank"><img src="https://opencollective.com/socketio/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/6/website" target="_blank"><img src="https://opencollective.com/socketio/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/7/website" target="_blank"><img src="https://opencollective.com/socketio/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/8/website" target="_blank"><img src="https://opencollective.com/socketio/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/9/website" target="_blank"><img src="https://opencollective.com/socketio/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/10/website" target="_blank"><img src="https://opencollective.com/socketio/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/11/website" target="_blank"><img src="https://opencollective.com/socketio/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/12/website" target="_blank"><img src="https://opencollective.com/socketio/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/13/website" target="_blank"><img src="https://opencollective.com/socketio/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/14/website" target="_blank"><img src="https://opencollective.com/socketio/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/15/website" target="_blank"><img src="https://opencollective.com/socketio/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/16/website" target="_blank"><img src="https://opencollective.com/socketio/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/17/website" target="_blank"><img src="https://opencollective.com/socketio/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/18/website" target="_blank"><img src="https://opencollective.com/socketio/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/19/website" target="_blank"><img src="https://opencollective.com/socketio/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/20/website" target="_blank"><img src="https://opencollective.com/socketio/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/21/website" target="_blank"><img src="https://opencollective.com/socketio/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/22/website" target="_blank"><img src="https://opencollective.com/socketio/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/23/website" target="_blank"><img src="https://opencollective.com/socketio/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/24/website" target="_blank"><img src="https://opencollective.com/socketio/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/25/website" target="_blank"><img src="https://opencollective.com/socketio/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/26/website" target="_blank"><img src="https://opencollective.com/socketio/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/27/website" target="_blank"><img src="https://opencollective.com/socketio/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/28/website" target="_blank"><img src="https://opencollective.com/socketio/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/socketio/backer/29/website" target="_blank"><img src="https://opencollective.com/socketio/backer/29/avatar.svg"></a>
io.sockets.on('connection', function (socket) {
socket.broadcast.emit('user connected');
socket.broadcast.json.send({ a: 'message' });
});
```
### Rooms
## Sponsors
Sometimes you want to put certain sockets in the same room, so that it's easy
to broadcast to all of them together.
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/socketio#sponsor)]
Think of this as built-in channels for sockets. Sockets `join` and `leave`
rooms in each socket.
<a href="https://opencollective.com/socketio/sponsor/0/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/1/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/2/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/3/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/4/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/5/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/6/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/7/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/8/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/9/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/10/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/11/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/12/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/13/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/14/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/15/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/16/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/17/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/18/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/19/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/20/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/21/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/22/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/23/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/24/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/25/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/26/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/27/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/28/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/socketio/sponsor/29/website" target="_blank"><img src="https://opencollective.com/socketio/sponsor/29/avatar.svg"></a>
#### Server side
```js
var io = require('socket.io').listen(80);
## License
io.sockets.on('connection', function (socket) {
socket.join('justin bieber fans');
socket.broadcast.to('justin bieber fans').emit('new fan');
io.sockets.in('rammstein fans').emit('new non-fan');
});
```
### Using it just as a cross-browser WebSocket
If you just want the WebSocket semantics, you can do that too.
Simply leverage `send` and listen on the `message` event:
#### Server side
```js
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on('message', function () { });
socket.on('disconnect', function () { });
});
```
#### Client side
```html
<script>
var socket = io.connect('http://localhost/');
socket.on('connect', function () {
socket.send('hi');
socket.on('message', function (msg) {
// my msg
});
});
</script>
```
### Changing configuration
Configuration in socket.io is TJ-style:
#### Server side
```js
var io = require('socket.io').listen(80);
io.configure(function () {
io.set('transports', ['websocket', 'flashsocket', 'xhr-polling']);
});
io.configure('development', function () {
io.set('transports', ['websocket', 'xhr-polling']);
io.enable('log');
});
```
## License
(The MIT License)
Copyright (c) 2011 Guillermo Rauch &lt;guillermo@learnboost.com&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
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.
[MIT](LICENSE)

View File

@@ -1,64 +0,0 @@
/**
* Module dependencies.
*/
var benchmark = require('benchmark')
, colors = require('colors')
, io = require('../')
, parser = io.parser
, suite = new benchmark.Suite('Decode packet');
suite.add('string', function () {
parser.decodePacket('4:::"2"');
});
suite.add('event', function () {
parser.decodePacket('5:::{"name":"woot"}');
});
suite.add('event+ack', function () {
parser.decodePacket('5:1+::{"name":"tobi"}');
});
suite.add('event+data', function () {
parser.decodePacket('5:::{"name":"edwald","args":[{"a": "b"},2,"3"]}');
});
suite.add('heartbeat', function () {
parser.decodePacket('2:::');
});
suite.add('error', function () {
parser.decodePacket('7:::2+0');
});
var payload = parser.encodePayload([
parser.encodePacket({ type: 'message', data: '5', endpoint: '' })
, parser.encodePacket({ type: 'message', data: '53d', endpoint: '' })
, parser.encodePacket({ type: 'message', data: 'foobar', endpoint: '' })
, parser.encodePacket({ type: 'message', data: 'foobarbaz', endpoint: '' })
, parser.encodePacket({ type: 'message', data: 'foobarbazfoobarbaz', endpoint: '' })
, parser.encodePacket({ type: 'message', data: 'foobarbaz', endpoint: '' })
, parser.encodePacket({ type: 'message', data: 'foobar', endpoint: '' })
]);
suite.add('payload', function () {
parser.decodePayload(payload);
});
suite.on('cycle', function (bench, details) {
console.log('\n' + suite.name.grey, details.name.white.bold);
console.log([
details.hz.toFixed(2).cyan + ' ops/sec'.grey
, details.count.toString().white + ' times executed'.grey
, 'benchmark took '.grey + details.times.elapsed.toString().white + ' sec.'.grey
,
].join(', '.grey));
});
if (!module.parent) {
suite.run();
} else {
module.exports = suite;
}

View File

@@ -1,90 +0,0 @@
/**
* Module dependencies.
*/
var benchmark = require('benchmark')
, colors = require('colors')
, io = require('../')
, parser = io.parser
, suite = new benchmark.Suite('Encode packet');
suite.add('string', function () {
parser.encodePacket({
type: 'json'
, endpoint: ''
, data: '2'
});
});
suite.add('event', function () {
parser.encodePacket({
type: 'event'
, name: 'woot'
, endpoint: ''
, args: []
});
});
suite.add('event+ack', function () {
parser.encodePacket({
type: 'json'
, id: 1
, ack: 'data'
, endpoint: ''
, data: { a: 'b' }
});
});
suite.add('event+data', function () {
parser.encodePacket({
type: 'event'
, name: 'edwald'
, endpoint: ''
, args: [{a: 'b'}, 2, '3']
});
});
suite.add('heartbeat', function () {
parser.encodePacket({
type: 'heartbeat'
, endpoint: ''
})
});
suite.add('error', function () {
parser.encodePacket({
type: 'error'
, reason: 'unauthorized'
, advice: 'reconnect'
, endpoint: ''
})
})
suite.add('payload', function () {
parser.encodePayload([
parser.encodePacket({ type: 'message', data: '5', endpoint: '' })
, parser.encodePacket({ type: 'message', data: '53d', endpoint: '' })
, parser.encodePacket({ type: 'message', data: 'foobar', endpoint: '' })
, parser.encodePacket({ type: 'message', data: 'foobarbaz', endpoint: '' })
, parser.encodePacket({ type: 'message', data: 'foobarbazfoobarbaz', endpoint: '' })
, parser.encodePacket({ type: 'message', data: 'foobarbaz', endpoint: '' })
, parser.encodePacket({ type: 'message', data: 'foobar', endpoint: '' })
]);
});
suite.on('cycle', function (bench, details) {
console.log('\n' + suite.name.grey, details.name.white.bold);
console.log([
details.hz.toFixed(2).cyan + ' ops/sec'.grey
, details.count.toString().white + ' times executed'.grey
, 'benchmark took '.grey + details.times.elapsed.toString().white + ' sec.'.grey
,
].join(', '.grey));
});
if (!module.parent) {
suite.run();
} else {
module.exports = suite;
}

View File

@@ -1,55 +0,0 @@
/**
* Benchmark runner dependencies
*/
var colors = require('colors')
, path = require('path');
/**
* Find all the benchmarks
*/
var benchmarks_files = process.env.BENCHMARKS.split(' ')
, all = [].concat(benchmarks_files)
, first = all.shift()
, benchmarks = {};
// find the benchmarks and load them all in our obj
benchmarks_files.forEach(function (file) {
benchmarks[file] = require(path.join(__dirname, '..', file));
});
// setup the complete listeners
benchmarks_files.forEach(function (file) {
var benchmark = benchmarks[file]
, next_file = all.shift()
, next = benchmarks[next_file];
/**
* Generate a oncomplete function for the tests, either we are done or we
* have more benchmarks to process.
*/
function complete () {
if (!next) {
console.log(
'\n\nBenchmark completed in'.grey
, (Date.now() - start).toString().green + ' ms'.grey
);
} else {
console.log('\nStarting benchmark '.grey + next_file.yellow);
next.run();
}
}
// attach the listener
benchmark.on('complete', complete);
});
/**
* Start the benchmark
*/
var start = Date.now();
console.log('Starting benchmark '.grey + first.yellow);
benchmarks[first].run();

619
docs/API.md Normal file
View File

@@ -0,0 +1,619 @@
## Table of Contents
- [Class: Server](#server)
- [new Server(httpServer[, options])](#new-serverhttpserver-options)
- [new Server(port[, options])](#new-serverport-options)
- [new Server(options)](#new-serveroptions)
- [server.sockets](#serversockets)
- [server.engine.generateId](#serverenginegenerateid)
- [server.serveClient([value])](#serverserveclientvalue)
- [server.path([value])](#serverpathvalue)
- [server.adapter([value])](#serveradaptervalue)
- [server.origins([value])](#serveroriginsvalue)
- [server.origins(fn)](#serveroriginsfn)
- [server.attach(httpServer[, options])](#serverattachhttpserver-options)
- [server.attach(port[, options])](#serverattachport-options)
- [server.listen(httpServer[, options])](#serverlistenhttpserver-options)
- [server.listen(port[, options])](#serverlistenport-options)
- [server.bind(engine)](#serverbindengine)
- [server.onconnection(socket)](#serveronconnectionsocket)
- [server.of(nsp)](#serverofnsp)
- [server.close([callback])](#serverclosecallback)
- [Class: Namespace](#namespace)
- [namespace.name](#namespacename)
- [namespace.connected](#namespaceconnected)
- [namespace.emit(eventName[, ...args])](#namespaceemiteventname-args)
- [namespace.clients(callback)](#namespaceclientscallback)
- [namespace.use(fn)](#namespaceusefn)
- [Event: 'connect'](#event-connect)
- [Event: 'connection'](#event-connect)
- [Flag: 'volatile'](#flag-volatile)
- [Flag: 'local'](#flag-local)
- [Class: Socket](#socket)
- [socket.id](#socketid)
- [socket.rooms](#socketrooms)
- [socket.client](#socketclient)
- [socket.conn](#socketconn)
- [socket.request](#socketrequest)
- [socket.use(fn)](#socketusefn)
- [socket.send([...args][, ack])](#socketsendargs-ack)
- [socket.emit(eventName[, ...args][, ack])](#socketemiteventname-args-ack)
- [socket.on(eventName, callback)](#socketoneventname-callback)
- [socket.once(eventName, listener)](#socketonceeventname-listener)
- [socket.removeListener(eventName, listener)](#socketremovelistenereventname-listener)
- [socket.removeAllListeners([eventName])](#socketremovealllistenerseventname)
- [socket.eventNames()](#socketeventnames)
- [socket.join(room[, callback])](#socketjoinroom-callback)
- [socket.join(rooms[, callback])](#socketjoinrooms-callback)
- [socket.leave(room[, callback])](#socketleaveroom-callback)
- [socket.to(room)](#sockettoroom)
- [socket.in(room)](#socketinroom)
- [socket.compress(value)](#socketcompressvalue)
- [socket.disconnect(close)](#socketdisconnectclose)
- [Flag: 'broadcast'](#flag-broadcast)
- [Flag: 'volatile'](#flag-volatile-1)
- [Event: 'disconnect'](#event-disconnect)
- [Event: 'error'](#event-error)
- [Event: 'disconnecting'](#event-disconnecting)
- [Class: Client](#client)
- [client.conn](#clientconn)
- [client.request](#clientrequest)
### Server
Exposed by `require('socket.io')`.
#### new Server(httpServer[, options])
- `httpServer` _(http.Server)_ the server to bind to.
- `options` _(Object)_
- `path` _(String)_: name of the path to capture (`/socket.io`)
- `serveClient` _(Boolean)_: whether to serve the client files (`true`)
- `adapter` _(Adapter)_: the adapter to use. Defaults to an instance of the `Adapter` that ships with socket.io which is memory based. See [socket.io-adapter](https://github.com/socketio/socket.io-adapter)
- `origins` _(String)_: the allowed origins (`*`)
- `allowRequest` _(Function)_: A function that receives a given handshake or upgrade request as its first parameter, and can decide whether to continue or not. The second argument is a function that needs to be called with the decided information: `fn(err, success)`, where `success` is a boolean value where false means that the request is rejected, and err is an error code.
- `parser` _(Parser)_: the parser to use. Defaults to an instance of the `Parser` that ships with socket.io. See [socket.io-parser](https://github.com/socketio/socket.io-parser).
Works with and without `new`:
```js
var io = require('socket.io')();
// or
var Server = require('socket.io');
var io = new Server();
```
The same options passed to socket.io are always passed to the `engine.io` `Server` that gets created. See engine.io [options](https://github.com/socketio/engine.io#methods-1) as reference.
Among those options:
- `pingTimeout` _(Number)_: how many ms without a pong packet to consider the connection closed (`60000`)
- `pingInterval` _(Number)_: how many ms before sending a new ping packet (`25000`).
Those two parameters will impact the delay before a client knows the server is not available anymore. For example, if the underlying TCP connection is not closed properly due to a network issue, a client may have to wait up to `pingTimeout + pingInterval` ms before getting a `disconnect` event.
- `transports` _(Array<String>)_: transports to allow connections to (`['polling', 'websocket']`).
**Note:** The order is important. By default, a long-polling connection is established first, and then upgraded to WebSocket if possible. Using `['websocket']` means there will be no fallback if a WebSocket connection cannot be opened.
#### new Server(port[, options])
- `port` _(Number)_ a port to listen to (a new `http.Server` will be created)
- `options` _(Object)_
See [above](#new-serverhttpserver-options) for available options.
#### new Server(options)
- `options` _(Object)_
See [above](#new-serverhttpserver-options) for available options.
#### server.sockets
* _(Namespace)_
The default (`/`) namespace.
#### server.serveClient([value])
- `value` _(Boolean)_
- **Returns** `Server|Boolean`
If `value` 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. If no arguments are supplied this method returns the current value.
```js
// 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);
```
#### server.path([value])
- `value` _(String)_
- **Returns** `Server|String`
Sets the path `value` 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([value])
- `value` _(Adapter)_
- **Returns** `Server|Adapter`
Sets the adapter `value`. Defaults to an instance of the `Adapter` that ships with socket.io which is memory based. See [socket.io-adapter](https://github.com/socketio/socket.io-adapter). If no arguments are supplied this method returns the current value.
#### server.origins([value])
- `value` _(String)_
- **Returns** `Server|String`
Sets the allowed origins `value`. Defaults to any origins being allowed. If no arguments are supplied this method returns the current value.
#### server.origins(fn)
- `fn` _(Function)_
- **Returns** `Server`
Provides a function taking 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](https://github.com/expressjs/cors).
#### server.attach(httpServer[, options])
- `httpServer` _(http.Server)_ the server to attach to
- `options` _(Object)_
Attaches the `Server` to an engine.io instance on `httpServer` with the supplied `options` (optionally).
### server.attach(port[, options])
- `port` _(Number)_ the port to listen on
- `options` _(Object)_
Attaches the `Server` to an engine.io instance on a new http.Server with the supplied `options` (optionally).
#### server.listen(httpServer[, options])
Synonym of [server.attach(httpServer[, options])](#serverattachhttpserver-options).
#### server.listen(port[, options])
Synonym of [server.attach(port[, options])](#serverattachport-options).
#### server.bind(engine)
- `engine` _(engine.Server)_
- **Returns** `Server`
Advanced use only. Binds the server to a specific engine.io `Server` (or compatible API) instance.
#### server.onconnection(socket)
- `socket` _(engine.Socket)_
- **Returns** `Server`
Advanced use only. Creates a new `socket.io` client from the incoming engine.io (or compatible API) `Socket`.
#### server.of(nsp)
- `nsp` _(String)_
- **Returns** `Namespace`
Initializes and retrieves the given `Namespace` by its pathname identifier `nsp`. If the namespace was already initialized it returns it immediately.
#### server.close([callback])
- `callback` _(Function)_
Closes the socket.io server. The `callback` argument is optional and will be called when all connections are closed.
```js
var Server = require('socket.io');
var PORT = 3030;
var server = require('http').Server();
var io = Server(PORT);
io.close(); // Close current server
server.listen(PORT); // PORT is free to use
io = Server(server);
```
#### server.engine.generateId
Overwrites the default method to generate your custom socket id.
The function is called with a node request object (`http.IncomingMessage`) as first parameter.
```js
io.engine.generateId = function (req) {
return "custom:id:" + custom_id++; // custom id must be unique
}
```
### Namespace
Represents a pool of sockets connected under a given scope identified
by a pathname (eg: `/chat`).
By default the client always connects to `/`.
#### namespace.name
* _(String)_
The namespace identifier property.
#### namespace.connected
* _(Object<Socket>)_
The hash of `Socket` objects that are connected to this namespace, indexed by `id`.
#### namespace.emit(eventName[, ...args])
- `eventName` _(String)_
- `args`
Emits an event to all connected clients. The following two are equivalent:
```js
var io = require('socket.io')();
io.emit('an event sent to all connected clients'); // main namespace
var chat = io.of('/chat');
chat.emit('an event sent to all connected clients in chat namespace');
```
#### namespace.clients(callback)
- `callback` _(Function)_
Gets a list of client IDs connected to this namespace (across all nodes if applicable).
```js
var io = require('socket.io')();
io.of('/chat').clients(function(error, clients){
if (error) throw error;
console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
});
```
An example to get all clients in namespace's room:
```js
var io = require('socket.io')();
io.of('/chat').in('general').clients(function(error, clients){
if (error) throw error;
console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
});
```
As with broadcasting, the default is all clients from the default namespace ('/'):
```js
var io = require('socket.io')();
io.clients(function(error, clients){
if (error) throw error;
console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]
});
```
#### namespace.use(fn)
- `fn` _(Function)_
Registers a middleware, which is a function that gets executed for every incoming `Socket`, and receives as parameters the socket and a function to optionally defer execution to the next registered middleware.
Errors passed to middleware callbacks are sent as special `error` packets to clients.
```js
var io = require('socket.io')();
io.use(function(socket, next){
if (socket.request.headers.cookie) return next();
next(new Error('Authentication error'));
});
```
#### Event: 'connect'
- `socket` _(Socket)_ socket connection with client
Fired upon a connection from client.
#### Event: 'connection'
Synonym of [Event: 'connect'](#event-connect).
#### Flag: 'volatile'
Sets a modifier for a subsequent event emission that the event data may be lost if the clients are not ready to receive messages (because of network slowness or other issues, or because theyre connected through long polling and is in the middle of a request-response cycle).
```js
io.volatile.emit('an event', { some: 'data' }); // the clients may or may not receive it
```
#### Flag: 'local'
Sets a modifier for a subsequent event emission that the event data will only be _broadcast_ to the current node (when the [Redis adapter](https://github.com/socketio/socket.io-redis) is used).
```js
io.local.emit('an event', { some: 'data' });
```
### 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.
It should be noted the `Socket` doesn't relate directly to the actual underlying TCP/IP `socket` and it is only the name of the class.
Within each `Namespace`, you can also define arbitrary channels (called `room`) that the `Socket` can join and leave. That provides a convenient way to broadcast to a group of `Socket`s (see `Socket#to` below).
The `Socket` class inherits from [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter). The `Socket` class overrides the `emit` method, and does not modify any other `EventEmitter` method. All methods documented here which also appear as `EventEmitter` methods (apart from `emit`) are implemented by `EventEmitter`, and documentation for `EventEmitter` applies.
#### socket.id
* _(String)_
A unique identifier for the session, that comes from the underlying `Client`.
#### socket.rooms
* _(Object)_
A hash of strings identifying the rooms this client is in, indexed by room name.
#### socket.client
* _(Client)_
A reference to the underlying `Client` object.
#### socket.conn
* _(engine.Socket)_
A reference to the underlying `Client` transport connection (engine.io `Socket` object). This allows access to the IO transport layer, which still (mostly) abstracts the actual TCP/IP socket.
#### 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.use(fn)
- `fn` _(Function)_
Registers a middleware, which is a function that gets executed for every incoming `Packet` and receives as parameter the packet and a function to optionally defer execution to the next registered middleware.
Errors passed to middleware callbacks are sent as special `error` packets to clients.
```js
var io = require('socket.io')();
io.on('connection', function(socket){
socket.use(function(packet, next){
if (packet.doge === true) return next();
next(new Error('Not a doge error'));
});
});
```
#### socket.send([...args][, ack])
- `args`
- `ack` _(Function)_
- **Returns** `Socket`
Sends a `message` event. See [socket.emit(eventName[, ...args][, ack])](#socketemiteventname-args-ack).
#### socket.emit(eventName[, ...args][, ack])
*(overrides `EventEmitter.emit`)*
- `eventName` _(String)_
- `args`
- `ack` _(Function)_
- **Returns** `Socket`
Emits an event to the socket identified by the string name. Any other parameters can be included. All serializable datastructures are supported, including `Buffer`.
```js
socket.emit('hello', 'world');
socket.emit('with-binary', 1, '2', { 3: '4', 5: new Buffer(6) });
```
The `ack` argument is optional and will be called with the client's answer.
```js
var io = require('socket.io')();
io.on('connection', function(client){
client.emit('an event', { some: 'data' });
client.emit('ferret', 'tobi', function (data) {
console.log(data); // data will be 'woot'
});
// the client code
// client.on('ferret', function (name, fn) {
// fn('woot');
// });
});
```
#### socket.on(eventName, callback)
*(inherited from `EventEmitter`)*
- `eventName` _(String)_
- `callback` _(Function)_
- **Returns** `Socket`
Register a new handler for the given event.
```js
socket.on('news', function (data) {
console.log(data);
});
```
#### socket.once(eventName, listener)
#### socket.removeListener(eventName, listener)
#### socket.removeAllListeners([eventName])
#### socket.eventNames()
Inherited from `EventEmitter` (along with other methods not mentioned here). See Node.js documentation for the `events` module.
#### socket.join(room[, callback])
- `room` _(String)_
- `callback` _(Function)_
- **Returns** `Socket` for chaining
Adds the client to the `room`, and fires optionally a callback with `err` signature (if any).
```js
io.on('connection', function(socket){
socket.join('room 237', function(){
console.log(socket.rooms); // [ <socket.id>, 'room 237' ]
io.to('room 237', 'a new user has joined the room'); // broadcast to everyone in the room
});
});
```
The mechanics of joining rooms are handled by the `Adapter` that has been configured (see `Server#adapter` above), defaulting to [socket.io-adapter](https://github.com/socketio/socket.io-adapter).
For your convenience, each socket automatically joins a room identified by this id (see `Socket#id`). This makes it easy to broadcast messages to other sockets:
```js
io.on('connection', function(client){
client.on('say to someone', function(id, msg){
// send a private message to the socket with the given id
client.broadcast.to(id).emit('my message', msg);
});
});
```
#### socket.join(rooms[, callback])
- `rooms` _(Array)_
- `callback` _(Function)_
- **Returns** `Socket` for chaining
Adds the client to the list of room, and fires optionally a callback with `err` signature (if any).
#### socket.leave(room[, callback])
- `room` _(String)_
- `callback` _(Function)_
- **Returns** `Socket` for chaining
Removes the client from `room`, and fires optionally a callback with `err` signature (if any).
**Rooms are left automatically upon disconnection**.
#### socket.to(room)
- `room` _(String)_
- **Returns** `Socket` for chaining
Sets a modifier for a subsequent event emission that the event will only be _broadcasted_ to clients that have joined the given `room`.
To emit to multiple rooms, you can call `to` several times.
```js
var io = require('socket.io')();
io.on('connection', function(client){
// to one room
client.to('others').emit('an event', { some: 'data' });
// to multiple rooms
client.to('room1').to('room2').emit('hello');
});
```
#### socket.in(room)
Synonym of [socket.to(room)](#sockettoroom).
#### socket.compress(value)
- `value` _(Boolean)_ whether to following packet will be compressed
- **Returns** `Socket` for chaining
Sets a modifier for a subsequent event emission that the event data will only be _compressed_ if the value is `true`. Defaults to `true` when you don't call the method.
#### socket.disconnect(close)
- `close` _(Boolean)_ whether to close the underlying connection
- **Returns** `Socket`
Disconnects this client. If value of close is `true`, closes the underlying connection. Otherwise, it just disconnects the namespace.
#### Flag: 'broadcast'
Sets a modifier for a subsequent event emission that the event data will only be _broadcast_ to every sockets but the sender.
```js
var io = require('socket.io')();
io.on('connection', function(socket){
socket.broadcast.emit('an event', { some: 'data' }); // everyone gets it but the sender
});
```
#### Flag: 'volatile'
Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to receive messages (because of network slowness or other issues, or because theyre connected through long polling and is in the middle of a request-response cycle).
```js
var io = require('socket.io')();
io.on('connection', function(socket){
socket.volatile.emit('an event', { some: 'data' }); // the client may or may not receive it
});
```
#### Event: 'disconnect'
- `reason` _(String)_ the reason of the disconnection (either client or server-side)
Fired upon disconnection.
#### Event: 'error'
- `error` _(Object)_ error object
Fired when an error occurs.
#### Event: 'disconnecting'
- `reason` _(String)_ the reason of the disconnection (either client or server-side)
Fired when the client is going to be disconnected (but hasn't left its `rooms` yet).
These are reserved events (along with `connect`, `newListener` and `removeListener`) which cannot be used as event names.
### Client
The `Client` class represents an incoming transport (engine.io) connection. A `Client` can be associated with many multiplexed `Socket`s that belong to different `Namespace`s.
#### client.conn
* _(engine.Socket)_
A reference to the underlying `engine.io` `Socket` connection.
#### client.request
* _(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`.

15
docs/README.md Normal file
View File

@@ -0,0 +1,15 @@
## Table of Contents
#### Getting started
- [Write a chat application](http://socket.io/get-started/chat/)
#### API Reference
- [Server API](API.md)
- [Client API](https://github.com/socketio/socket.io-client/blob/master/docs/API.md)
#### Advanced topics
- [Emit cheatsheet](emit.md)

58
docs/emit.md Normal file
View File

@@ -0,0 +1,58 @@
## Emit cheatsheet
```js
io.on('connect', onConnect);
function onConnect(socket){
// sending to the client
socket.emit('hello', 'can you hear me?', 1, 2, 'abc');
// sending to all clients except sender
socket.broadcast.emit('broadcast', 'hello friends!');
// sending to all clients in 'game' room except sender
socket.to('game').emit('nice game', "let's play a game");
// sending to all clients in 'game1' and/or in 'game2' room, except sender
socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");
// sending to all clients in 'game' room, including sender
io.in('game').emit('big-announcement', 'the game will start soon');
// sending to all clients in namespace 'myNamespace', including sender
io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');
// sending to a specific room in a specific namespace, including sender
io.of('myNamespace').to('room').emit('event', 'message');
// sending to individual socketid (private message)
socket.to(<socketid>).emit('hey', 'I just met you');
// sending with acknowledgement
socket.emit('question', 'do you think so?', function (answer) {});
// sending without compression
socket.compress(false).emit('uncompressed', "that's rough");
// sending a message that might be dropped if the client is not ready to receive messages
socket.volatile.emit('maybe', 'do you really need it?');
// sending to all clients on this node (when using multiple nodes)
io.local.emit('hi', 'my lovely babies');
};
```
**Note:** The following events are reserved and should not be used as event names by your application:
- `error`
- `connect`
- `disconnect`
- `disconnecting`
- `newListener`
- `removeListener`
- `ping`
- `pong`

25
examples/chat/README.md Normal file
View File

@@ -0,0 +1,25 @@
# Socket.IO Chat
A simple chat demo for socket.io
## How to use
```
$ cd socket.io
$ npm install
$ cd examples/chat
$ npm install
$ npm start
```
And point your browser to `http://localhost:3000`. Optionally, specify
a port by supplying the `PORT` env variable.
## Features
- Multiple users can join a chat room by each entering a unique username
on website load.
- Users can type chat messages to the chat room.
- A notification is sent to all users when a user joins or leaves
the chatroom.

View File

@@ -1,80 +0,0 @@
/**
* Module dependencies.
*/
var express = require('express')
, stylus = require('stylus')
, nib = require('nib')
, sio = require('../../lib/socket.io');
/**
* App.
*/
var app = express.createServer();
/**
* App configuration.
*/
app.configure(function () {
app.use(stylus.middleware({ src: __dirname + '/public', compile: compile }));
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname);
app.set('view engine', 'jade');
function compile (str, path) {
return stylus(str)
.set('filename', path)
.use(nib());
};
});
/**
* App routes.
*/
app.get('/', function (req, res) {
res.render('index', { layout: false });
});
/**
* App listen.
*/
app.listen(3000, function () {
var addr = app.address();
console.log(' app listening on http://' + addr.address + ':' + addr.port);
});
/**
* Socket.IO server (single process only)
*/
var io = sio.listen(app)
, nicknames = {};
io.sockets.on('connection', function (socket) {
socket.on('user message', function (msg) {
socket.broadcast.emit('user message', socket.nickname, msg);
});
socket.on('nickname', function (nick, fn) {
if (nicknames[nick]) {
fn(true);
} else {
fn(false);
nicknames[nick] = socket.nickname = nick;
socket.broadcast.emit('announcement', nick + ' connected');
io.sockets.emit('nicknames', nicknames);
}
});
socket.on('disconnect', function () {
if (!socket.nickname) return;
delete nicknames[socket.nickname];
socket.broadcast.emit('announcement', socket.nickname + ' disconnected');
socket.broadcast.emit('nicknames', nicknames);
});
});

View File

@@ -1,83 +0,0 @@
doctype 5
html
head
link(href='/stylesheets/style.css', rel='stylesheet')
script(src='http://code.jquery.com/jquery-1.6.1.min.js')
script(src='/socket.io/socket.io.js')
script
// socket.io specific code
var socket = io.connect();
socket.on('connect', function () {
$('#chat').addClass('connected');
});
socket.on('announcement', function (msg) {
$('#lines').append($('<p>').append($('<em>').text(msg)));
});
socket.on('nicknames', function (nicknames) {
$('#nicknames').empty().append($('<span>Online: </span>'));
for (var i in nicknames) {
$('#nicknames').append($('<b>').text(nicknames[i]));
}
});
socket.on('user message', message);
socket.on('reconnect', function () {
$('#lines').remove();
message('System', 'Reconnected to the server');
});
socket.on('reconnecting', function () {
message('System', 'Attempting to re-connect to the server');
});
socket.on('error', function (e) {
message('System', e ? e : 'A unknown error occurred');
});
function message (from, msg) {
$('#lines').append($('<p>').append($('<b>').text(from), msg));
}
// dom manipulation
$(function () {
$('#set-nickname').submit(function (ev) {
socket.emit('nickname', $('#nick').val(), function (set) {
if (!set) {
clear();
return $('#chat').addClass('nickname-set');
}
$('#nickname-err').css('visibility', 'visible');
});
return false;
});
$('#send-message').submit(function () {
message('me', $('#message').val());
socket.emit('user message', $('#message').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear () {
$('#message').val('').focus();
};
});
body
#chat
#nickname
form.wrap#set-nickname
p Please type in your nickname and press enter.
input#nick
p#nickname-err Nickname already in use
#connecting
.wrap Connecting to socket.io server
#messages
#nicknames
#lines
form#send-message
input#message
button Send

75
examples/chat/index.js Normal file
View File

@@ -0,0 +1,75 @@
// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('../..')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
// Routing
app.use(express.static(__dirname + '/public'));
// Chatroom
var numUsers = 0;
io.on('connection', function (socket) {
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (username) {
if (addedUser) return;
// we store the username in the socket session for this client
socket.username = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
if (addedUser) {
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
}
});
});

View File

@@ -1,11 +1,15 @@
{
"name": "chat.io"
, "description": "example chat application with socket.io"
, "version": "0.0.1"
, "dependencies": {
"express": "2.5.5"
, "jade": "0.16.4"
, "stylus": "0.19.0"
, "nib": "0.2.0"
}
"name": "socket.io-chat",
"version": "0.0.0",
"description": "A simple chat client using socket.io",
"main": "index.js",
"author": "Grant Timmerman",
"private": true,
"license": "BSD",
"dependencies": {
"express": "4.13.4"
},
"scripts": {
"start": "node index.js"
}
}

View File

@@ -0,0 +1,28 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.IO Chat Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<ul class="pages">
<li class="chat page">
<div class="chatArea">
<ul class="messages"></ul>
</div>
<input class="inputMessage" placeholder="Type here..."/>
</li>
<li class="login page">
<div class="form">
<h3 class="title">What's your nickname?</h3>
<input class="usernameInput" type="text" maxlength="14" />
</div>
</li>
</ul>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="/main.js"></script>
</body>
</html>

View File

@@ -0,0 +1,282 @@
$(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
// Initialize variables
var $window = $(window);
var $usernameInput = $('.usernameInput'); // Input for username
var $messages = $('.messages'); // Messages area
var $inputMessage = $('.inputMessage'); // Input message input box
var $loginPage = $('.login.page'); // The login page
var $chatPage = $('.chat.page'); // The chatroom page
// Prompt for setting a username
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput.focus();
var socket = io();
function addParticipantsMessage (data) {
var message = '';
if (data.numUsers === 1) {
message += "there's 1 participant";
} else {
message += "there are " + data.numUsers + " participants";
}
log(message);
}
// Sets the client's username
function setUsername () {
username = cleanInput($usernameInput.val().trim());
// If the username is valid
if (username) {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
// Tell the server your username
socket.emit('add user', username);
}
}
// Sends a chat message
function sendMessage () {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
message = cleanInput(message);
// if there is a non-empty message and a socket connection
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
// tell server to execute 'new message' and send along one parameter
socket.emit('new message', message);
}
}
// Log a message
function log (message, options) {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// Adds the visual chat message to the message list
function addChatMessage (data, options) {
// Don't fade the message in if there is an 'X was typing'
var $typingMessages = getTypingMessages(data);
options = options || {};
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// Adds the visual chat typing message
function addChatTyping (data) {
data.typing = true;
data.message = 'is typing';
addChatMessage(data);
}
// Removes the visual chat typing message
function removeChatTyping (data) {
getTypingMessages(data).fadeOut(function () {
$(this).remove();
});
}
// Adds a message element to the messages and scrolls to the bottom
// el - The element to add as a message
// options.fade - If the element should fade-in (default = true)
// options.prepend - If the element should prepend
// all other messages (default = false)
function addMessageElement (el, options) {
var $el = $(el);
// Setup default options
if (!options) {
options = {};
}
if (typeof options.fade === 'undefined') {
options.fade = true;
}
if (typeof options.prepend === 'undefined') {
options.prepend = false;
}
// Apply options
if (options.fade) {
$el.hide().fadeIn(FADE_TIME);
}
if (options.prepend) {
$messages.prepend($el);
} else {
$messages.append($el);
}
$messages[0].scrollTop = $messages[0].scrollHeight;
}
// Prevents input from having injected markup
function cleanInput (input) {
return $('<div/>').text(input).text();
}
// Updates the typing event
function updateTyping () {
if (connected) {
if (!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
// Gets the 'X is typing' messages of a user
function getTypingMessages (data) {
return $('.typing.message').filter(function (i) {
return $(this).data('username') === data.username;
});
}
// Gets the color of a username through our hash function
function getUsernameColor (username) {
// Compute hash code
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// Calculate color
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
}
// Keyboard events
$window.keydown(function (event) {
// Auto-focus the current input when a key is typed
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// When the client hits ENTER on their keyboard
if (event.which === 13) {
if (username) {
sendMessage();
socket.emit('stop typing');
typing = false;
} else {
setUsername();
}
}
});
$inputMessage.on('input', function() {
updateTyping();
});
// Click events
// Focus input when clicking anywhere on login page
$loginPage.click(function () {
$currentInput.focus();
});
// Focus input when clicking on the message input's border
$inputMessage.click(function () {
$inputMessage.focus();
});
// Socket events
// Whenever the server emits 'login', log the login message
socket.on('login', function (data) {
connected = true;
// Display the welcome message
var message = "Welcome to Socket.IO Chat ";
log(message, {
prepend: true
});
addParticipantsMessage(data);
});
// Whenever the server emits 'new message', update the chat body
socket.on('new message', function (data) {
addChatMessage(data);
});
// Whenever the server emits 'user joined', log it in the chat body
socket.on('user joined', function (data) {
log(data.username + ' joined');
addParticipantsMessage(data);
});
// Whenever the server emits 'user left', log it in the chat body
socket.on('user left', function (data) {
log(data.username + ' left');
addParticipantsMessage(data);
removeChatTyping(data);
});
// Whenever the server emits 'typing', show the typing message
socket.on('typing', function (data) {
addChatTyping(data);
});
// Whenever the server emits 'stop typing', kill the typing message
socket.on('stop typing', function (data) {
removeChatTyping(data);
});
socket.on('disconnect', function () {
log('you have been disconnected');
});
socket.on('reconnect', function () {
log('you have been reconnected');
if (username) {
socket.emit('add user', username);
}
});
socket.on('reconnect_error', function () {
log('attempt to reconnect has failed');
});
});

View File

@@ -0,0 +1,149 @@
/* Fix user-agent */
* {
box-sizing: border-box;
}
html {
font-weight: 300;
-webkit-font-smoothing: antialiased;
}
html, input {
font-family:
"HelveticaNeue-Light",
"Helvetica Neue Light",
"Helvetica Neue",
Helvetica,
Arial,
"Lucida Grande",
sans-serif;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
ul {
list-style: none;
word-wrap: break-word;
}
/* Pages */
.pages {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
.page {
height: 100%;
position: absolute;
width: 100%;
}
/* Login Page */
.login.page {
background-color: #000;
}
.login.page .form {
height: 100px;
margin-top: -100px;
position: absolute;
text-align: center;
top: 50%;
width: 100%;
}
.login.page .form .usernameInput {
background-color: transparent;
border: none;
border-bottom: 2px solid #fff;
outline: none;
padding-bottom: 15px;
text-align: center;
width: 400px;
}
.login.page .title {
font-size: 200%;
}
.login.page .usernameInput {
font-size: 200%;
letter-spacing: 3px;
}
.login.page .title, .login.page .usernameInput {
color: #fff;
font-weight: 100;
}
/* Chat page */
.chat.page {
display: none;
}
/* Font */
.messages {
font-size: 150%;
}
.inputMessage {
font-size: 100%;
}
.log {
color: gray;
font-size: 70%;
margin: 5px;
text-align: center;
}
/* Messages */
.chatArea {
height: 100%;
padding-bottom: 60px;
}
.messages {
height: 100%;
margin: 0;
overflow-y: scroll;
padding: 10px 20px 10px 20px;
}
.message.typing .messageBody {
color: gray;
}
.username {
font-weight: 700;
overflow: hidden;
padding-right: 15px;
text-align: right;
}
/* Input */
.inputMessage {
border: 10px solid #000;
bottom: 0;
height: 60px;
left: 0;
outline: none;
padding-left: 10px;
position: absolute;
right: 0;
width: 100%;
}

View File

@@ -1,96 +0,0 @@
border-radius(n)
-webkit-border-radius n
-moz-border-radius n
border-radius n
// replace str with val
replace(expr, str, val)
expr = clone(expr)
for e, i in expr
if str == e
expr[i] = val
expr
// normalize gradient point (webkit)
grad-point(pos)
if length(pos) == 1
return left pos if pos in (top bottom)
return pos top if pos in (left right)
else if pos[0] in (top bottom)
pos[1] pos[0]
else
pos
// implicit color stop position
pos-in-stops(i, stops)
len = length(stops)
if len - 1 == i
100%
else if i
unit(i / len * 100, '%')
else
0%
// normalize color stops
// - (color pos) -> (pos color)
// - (color) -> (implied-pos color)
normalize-stops(stops)
stops = clone(stops)
for stop, i in stops
if length(stop) == 1
color = stop[0]
stop[0] = pos-in-stops(i, stops)
stop[1] = color
else if typeof(stop[1]) == 'unit'
pos = stop[1]
stop[1] = stop[0]
stop[0] = pos
stops
// join color stops with the given translation function
join-stops(stops, translate)
str = ''
len = length(stops)
for stop, i in stops
str += ', ' if i
pos = stop[0]
color = stop[1]
str += translate(color, pos)
unquote(str)
// webkit translation function
webkit-stop(color, pos)
s('color-stop(%d, %s)', pos / 100, color)
// mozilla translation function
moz-stop(color, pos)
s('%s %s', color, pos)
// create a linear gradient with the given start
// position, followed by color stops
linear-gradient(start, stops...)
error('color stops required') unless length(stops)
prop = current-property[0]
val = current-property[1]
stops = normalize-stops(stops)
// webkit
end = grad-point(opposite-position(start))
webkit = s('-webkit-gradient(linear, %s, %s, %s)', grad-point(start), end, join-stops(stops, webkit-stop))
add-property(prop, replace(val, '__CALL__', webkit))
// moz
stops = join-stops(stops, moz-stop)
moz = s('-moz-linear-gradient(%s, %s)', start, stops)
add-property(prop, replace(val, '__CALL__', moz))
// literal
s('linear-gradient(%s, %s)', start, stops)

View File

@@ -1,188 +0,0 @@
#chat,
#nickname,
#messages {
width: 600px;
}
#chat {
position: relative;
border: 1px solid #ccc;
}
#nickname,
#connecting {
position: absolute;
height: 410px;
z-index: 100;
left: 0;
top: 0;
background: #fff;
text-align: center;
width: 600px;
font: 15px Georgia;
color: #666;
display: block;
}
#nickname .wrap,
#connecting .wrap {
padding-top: 150px;
}
#nickname input {
border: 1px solid #ccc;
padding: 10px;
}
#nickname input:focus {
border-color: #999;
outline: 0;
}
#nickname #nickname-err {
color: #8b0000;
font-size: 12px;
visibility: hidden;
}
.connected #connecting {
display: none;
}
.nickname-set #nickname {
display: none;
}
#messages {
height: 380px;
background: #eee;
}
#messages em {
text-shadow: 0 1px 0 #fff;
color: #999;
}
#messages p {
padding: 0;
margin: 0;
font: 12px Helvetica, Arial;
padding: 5px 10px;
}
#messages p b {
display: inline-block;
padding-right: 10px;
}
#messages p:nth-child(even) {
background: #fafafa;
}
#messages #nicknames {
background: #ccc;
padding: 2px 4px 4px;
font: 11px Helvetica;
}
#messages #nicknames span {
color: #000;
}
#messages #nicknames b {
display: inline-block;
color: #fff;
background: #999;
padding: 3px 6px;
margin-right: 5px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
text-shadow: 0 1px 0 #666;
}
#messages #lines {
height: 355px;
overflow: auto;
overflow-x: hidden;
overflow-y: auto;
}
#messages #lines::-webkit-scrollbar {
width: 6px;
height: 6px;
}
#messages #lines::-webkit-scrollbar-button:start:decrement,
#messages #lines ::-webkit-scrollbar-button:end:increment {
display: block;
height: 10px;
}
#messages #lines::-webkit-scrollbar-button:vertical:increment {
background-color: #fff;
}
#messages #lines::-webkit-scrollbar-track-piece {
background-color: #fff;
-webkit-border-radius: 3px;
}
#messages #lines::-webkit-scrollbar-thumb:vertical {
height: 50px;
background-color: #ccc;
-webkit-border-radius: 3px;
}
#messages #lines::-webkit-scrollbar-thumb:horizontal {
width: 50px;
background-color: #fff;
-webkit-border-radius: 3px;
}
#send-message {
background: #fff;
position: relative;
}
#send-message input {
border: none;
height: 30px;
padding: 0 10px;
line-height: 30px;
vertical-align: middle;
width: 580px;
}
#send-message input:focus {
outline: 0;
}
#send-message button {
position: absolute;
top: 5px;
right: 5px;
}
button {
margin: 0;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
display: inline-block;
text-decoration: none;
background: #43a1f7;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #43a1f7), color-stop(1, #377ad0));
background: -webkit-linear-gradient(top, #43a1f7 0%, #377ad0 100%);
background: -moz-linear-gradient(top, #43a1f7 0%, #377ad0 100%);
background: linear-gradient(top, #43a1f7 0%, #377ad0 100%);
border: 1px solid #2e70c4;
-webkit-border-radius: 16px;
-moz-border-radius: 16px;
border-radius: 16px;
color: #fff;
font-family: "lucida grande", sans-serif;
font-size: 11px;
font-weight: normal;
line-height: 1;
padding: 3px 10px 5px 10px;
text-align: center;
text-shadow: 0 -1px 1px #2d6dc0;
}
button:hover,
button.hover {
background: darker;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #43a1f7), color-stop(1, #2e70c4));
background: -webkit-linear-gradient(top, #43a1f7 0%, #2e70c4 100%);
background: -moz-linear-gradient(top, #43a1f7 0%, #2e70c4 100%);
background: linear-gradient(top, #43a1f7 0%, #2e70c4 100%);
border: 1px solid #2e70c4;
cursor: pointer;
text-shadow: 0 -1px 1px #2c6bbb;
}
button:active,
button.active {
background: #2e70c4;
border: 1px solid #2e70c4;
border-bottom: 1px solid #2861aa;
text-shadow: 0 -1px 1px #2b67b5;
}
button:focus,
button.focus {
outline: none;
-webkit-box-shadow: 0 1px 0 0 rgba(255,255,255,0.4), 0 0 4px 0 #377ad0;
-moz-box-shadow: 0 1px 0 0 rgba(255,255,255,0.4), 0 0 4px 0 #377ad0;
box-shadow: 0 1px 0 0 rgba(255,255,255,0.4), 0 0 4px 0 #377ad0;
}

View File

@@ -1,118 +0,0 @@
@import 'nib'
#chat, #nickname, #messages
width 600px
#chat
position relative
border 1px solid #ccc
#nickname, #connecting
position absolute
height 410px
z-index 100
left 0
top 0
background #fff
text-align center
width 600px
font 15px Georgia
color #666
display block
.wrap
padding-top 150px
#nickname
input
border 1px solid #ccc
padding 10px
&:focus
border-color #999
outline 0
#nickname-err
color darkred
font-size 12px
visibility hidden
.connected
#connecting
display none
.nickname-set
#nickname
display none
#messages
height 380px
background #eee
em
text-shadow 0 1px 0 #fff
color #999
p
padding 0
margin 0
font 12px Helvetica, Arial
padding 5px 10px
b
display inline-block
padding-right 10px
p:nth-child(even)
background #fafafa
#nicknames
background #ccc
padding 2px 4px 4px
font 11px Helvetica
span
color black
b
display inline-block
color #fff
background #999
padding 3px 6px
margin-right 5px
border-radius 10px
text-shadow 0 1px 0 #666
#lines
height 355px
overflow auto
overflow-x hidden
overflow-y auto
&::-webkit-scrollbar
width 6px
height 6px
&::-webkit-scrollbar-button:start:decrement, ::-webkit-scrollbar-button:end:increment
display block
height 10px
&::-webkit-scrollbar-button:vertical:increment
background-color #fff
&::-webkit-scrollbar-track-piece
background-color #fff
-webkit-border-radius 3px
&::-webkit-scrollbar-thumb:vertical
height 50px
background-color #ccc
-webkit-border-radius 3px
&::-webkit-scrollbar-thumb:horizontal
width 50px
background-color #fff
-webkit-border-radius 3px
#send-message
background #fff
position relative
input
border none
height 30px
padding 0 10px
line-height 30px
vertical-align middle
width 580px
&:focus
outline 0
button
position absolute
top 5px
right 5px
button
download-button()

View File

@@ -0,0 +1,31 @@
# Socket.IO Chat with haproxy & redis
A simple chat demo for socket.io
## How to use
Install [Docker Compose](https://docs.docker.com/compose/install/), then:
```
$ docker-compose up -d
```
And then point your browser to `http://localhost:3000`.
This will start four Socket.IO nodes, behind a haproxy instance which will loadbalance the requests (using a cookie for sticky sessions, see [cookie](https://cbonte.github.io/haproxy-dconv/1.7/configuration.html#4.2-cookie)).
Each node connects to the redis backend, which will enable to broadcast to every client, no matter which node it is currently connected to.
```
# you can kill a given node, the client should reconnect to another node
$ docker-compose stop server-george
```
## Features
- Multiple users can join a chat room by each entering a unique username
on website load.
- Users can type chat messages to the chat room.
- A notification is sent to all users when a user joins or leaves
the chatroom.

View File

@@ -0,0 +1,51 @@
haproxy:
build: ./haproxy
links:
- server-john
- server-paul
- server-george
- server-ringo
ports:
- "3000:80"
server-john:
build: ./server
links:
- redis
expose:
- "3000"
environment:
- NAME=John
server-paul:
build: ./server
links:
- redis
expose:
- "3000"
environment:
- NAME=Paul
server-george:
build: ./server
links:
- redis
expose:
- "3000"
environment:
- NAME=George
server-ringo:
build: ./server
links:
- redis
expose:
- "3000"
environment:
- NAME=Ringo
redis:
image: redis:alpine
expose:
- "6379"

View File

@@ -0,0 +1,2 @@
FROM haproxy:1.7-alpine
COPY haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg

View File

@@ -0,0 +1,31 @@
# Reference: http://blog.haproxy.com/2012/11/07/websockets-load-balancing-with-haproxy/
global
daemon
maxconn 4096
nbproc 2
defaults
mode http
balance roundrobin
option http-server-close
timeout connect 5s
timeout client 30s
timeout client-fin 30s
timeout server 30s
timeout tunnel 1h
default-server inter 1s rise 2 fall 1 on-marked-down shutdown-sessions
option forwardfor
listen chat
bind *:80
default_backend nodes
backend nodes
option httpchk HEAD /health
http-check expect status 200
cookie serverid insert
server john server-john:3000 cookie john check
server paul server-paul:3000 cookie paul check
server george server-george:3000 cookie george check
server ringo server-ringo:3000 cookie ringo check

View File

@@ -0,0 +1,15 @@
FROM mhart/alpine-node:6
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Bundle app source
COPY . /usr/src/app
EXPOSE 3000
CMD [ "npm", "start" ]

View File

@@ -0,0 +1,87 @@
// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var redis = require('socket.io-redis');
var port = process.env.PORT || 3000;
var serverName = process.env.NAME || 'Unknown';
io.adapter(redis({ host: 'redis', port: 6379 }));
server.listen(port, function () {
console.log('Server listening at port %d', port);
console.log('Hello, I\'m %s, how can I help?', serverName);
});
// Routing
app.use(express.static(__dirname + '/public'));
// Health check
app.head('/health', function (req, res) {
res.sendStatus(200);
});
// Chatroom
var numUsers = 0;
io.on('connection', function (socket) {
socket.emit('my-name-is', serverName);
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (username) {
if (addedUser) return;
// we store the username in the socket session for this client
socket.username = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
if (addedUser) {
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
}
});
});

View File

@@ -0,0 +1,17 @@
{
"name": "socket.io-chat",
"version": "0.0.0",
"description": "A simple chat client using socket.io",
"main": "index.js",
"author": "Grant Timmerman",
"private": true,
"license": "BSD",
"dependencies": {
"express": "4.13.4",
"socket.io": "^1.7.2",
"socket.io-redis": "^3.0.0"
},
"scripts": {
"start": "node index.js"
}
}

View File

@@ -0,0 +1,28 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.IO Chat Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<ul class="pages">
<li class="chat page">
<div class="chatArea">
<ul class="messages"></ul>
</div>
<input class="inputMessage" placeholder="Type here..."/>
</li>
<li class="login page">
<div class="form">
<h3 class="title">What's your nickname?</h3>
<input class="usernameInput" type="text" maxlength="14" />
</div>
</li>
</ul>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="/main.js"></script>
</body>
</html>

View File

@@ -0,0 +1,286 @@
$(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
// Initialize variables
var $window = $(window);
var $usernameInput = $('.usernameInput'); // Input for username
var $messages = $('.messages'); // Messages area
var $inputMessage = $('.inputMessage'); // Input message input box
var $loginPage = $('.login.page'); // The login page
var $chatPage = $('.chat.page'); // The chatroom page
// Prompt for setting a username
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput.focus();
var socket = io();
function addParticipantsMessage (data) {
var message = '';
if (data.numUsers === 1) {
message += "there's 1 participant";
} else {
message += "there are " + data.numUsers + " participants";
}
log(message);
}
// Sets the client's username
function setUsername () {
username = cleanInput($usernameInput.val().trim());
// If the username is valid
if (username) {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
// Tell the server your username
socket.emit('add user', username);
}
}
// Sends a chat message
function sendMessage () {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
message = cleanInput(message);
// if there is a non-empty message and a socket connection
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
// tell server to execute 'new message' and send along one parameter
socket.emit('new message', message);
}
}
// Log a message
function log (message, options) {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// Adds the visual chat message to the message list
function addChatMessage (data, options) {
// Don't fade the message in if there is an 'X was typing'
var $typingMessages = getTypingMessages(data);
options = options || {};
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// Adds the visual chat typing message
function addChatTyping (data) {
data.typing = true;
data.message = 'is typing';
addChatMessage(data);
}
// Removes the visual chat typing message
function removeChatTyping (data) {
getTypingMessages(data).fadeOut(function () {
$(this).remove();
});
}
// Adds a message element to the messages and scrolls to the bottom
// el - The element to add as a message
// options.fade - If the element should fade-in (default = true)
// options.prepend - If the element should prepend
// all other messages (default = false)
function addMessageElement (el, options) {
var $el = $(el);
// Setup default options
if (!options) {
options = {};
}
if (typeof options.fade === 'undefined') {
options.fade = true;
}
if (typeof options.prepend === 'undefined') {
options.prepend = false;
}
// Apply options
if (options.fade) {
$el.hide().fadeIn(FADE_TIME);
}
if (options.prepend) {
$messages.prepend($el);
} else {
$messages.append($el);
}
$messages[0].scrollTop = $messages[0].scrollHeight;
}
// Prevents input from having injected markup
function cleanInput (input) {
return $('<div/>').text(input).text();
}
// Updates the typing event
function updateTyping () {
if (connected) {
if (!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
// Gets the 'X is typing' messages of a user
function getTypingMessages (data) {
return $('.typing.message').filter(function (i) {
return $(this).data('username') === data.username;
});
}
// Gets the color of a username through our hash function
function getUsernameColor (username) {
// Compute hash code
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// Calculate color
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
}
// Keyboard events
$window.keydown(function (event) {
// Auto-focus the current input when a key is typed
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// When the client hits ENTER on their keyboard
if (event.which === 13) {
if (username) {
sendMessage();
socket.emit('stop typing');
typing = false;
} else {
setUsername();
}
}
});
$inputMessage.on('input', function() {
updateTyping();
});
// Click events
// Focus input when clicking anywhere on login page
$loginPage.click(function () {
$currentInput.focus();
});
// Focus input when clicking on the message input's border
$inputMessage.click(function () {
$inputMessage.focus();
});
// Socket events
// Whenever the server emits 'login', log the login message
socket.on('login', function (data) {
connected = true;
// Display the welcome message
var message = "Welcome to Socket.IO Chat ";
log(message, {
prepend: true
});
addParticipantsMessage(data);
});
// Whenever the server emits 'new message', update the chat body
socket.on('new message', function (data) {
addChatMessage(data);
});
// Whenever the server emits 'user joined', log it in the chat body
socket.on('user joined', function (data) {
log(data.username + ' joined');
addParticipantsMessage(data);
});
// Whenever the server emits 'user left', log it in the chat body
socket.on('user left', function (data) {
log(data.username + ' left');
addParticipantsMessage(data);
removeChatTyping(data);
});
// Whenever the server emits 'typing', show the typing message
socket.on('typing', function (data) {
addChatTyping(data);
});
// Whenever the server emits 'stop typing', kill the typing message
socket.on('stop typing', function (data) {
removeChatTyping(data);
});
socket.on('disconnect', function () {
log('you have been disconnected');
});
socket.on('reconnect', function () {
log('you have been reconnected');
if (username) {
socket.emit('add user', username);
}
});
socket.on('reconnect_error', function () {
log('attempt to reconnect has failed');
});
socket.on('my-name-is', function (serverName) {
log('host is now ' + serverName);
})
});

View File

@@ -0,0 +1,149 @@
/* Fix user-agent */
* {
box-sizing: border-box;
}
html {
font-weight: 300;
-webkit-font-smoothing: antialiased;
}
html, input {
font-family:
"HelveticaNeue-Light",
"Helvetica Neue Light",
"Helvetica Neue",
Helvetica,
Arial,
"Lucida Grande",
sans-serif;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
ul {
list-style: none;
word-wrap: break-word;
}
/* Pages */
.pages {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
.page {
height: 100%;
position: absolute;
width: 100%;
}
/* Login Page */
.login.page {
background-color: #000;
}
.login.page .form {
height: 100px;
margin-top: -100px;
position: absolute;
text-align: center;
top: 50%;
width: 100%;
}
.login.page .form .usernameInput {
background-color: transparent;
border: none;
border-bottom: 2px solid #fff;
outline: none;
padding-bottom: 15px;
text-align: center;
width: 400px;
}
.login.page .title {
font-size: 200%;
}
.login.page .usernameInput {
font-size: 200%;
letter-spacing: 3px;
}
.login.page .title, .login.page .usernameInput {
color: #fff;
font-weight: 100;
}
/* Chat page */
.chat.page {
display: none;
}
/* Font */
.messages {
font-size: 150%;
}
.inputMessage {
font-size: 100%;
}
.log {
color: gray;
font-size: 70%;
margin: 5px;
text-align: center;
}
/* Messages */
.chatArea {
height: 100%;
padding-bottom: 60px;
}
.messages {
height: 100%;
margin: 0;
overflow-y: scroll;
padding: 10px 20px 10px 20px;
}
.message.typing .messageBody {
color: gray;
}
.username {
font-weight: 700;
overflow: hidden;
padding-right: 15px;
text-align: right;
}
/* Input */
.inputMessage {
border: 10px solid #000;
bottom: 0;
height: 60px;
left: 0;
outline: none;
padding-left: 10px;
position: absolute;
right: 0;
width: 100%;
}

View File

@@ -0,0 +1,31 @@
# Socket.IO Chat with httpd & redis
A simple chat demo for socket.io
## How to use
Install [Docker Compose](https://docs.docker.com/compose/install/), then:
```
$ docker-compose up -d
```
And then point your browser to `http://localhost:3000`.
This will start four Socket.IO nodes, behind a httpd proxy which will loadbalance the requests (using a cookie for sticky sessions, see [cookie](http://httpd.apache.org/docs/2.4/fr/mod/mod_proxy_balancer.html)).
Each node connects to the redis backend, which will enable to broadcast to every client, no matter which node it is currently connected to.
```
# you can kill a given node, the client should reconnect to another node
$ docker-compose stop server-george
```
## Features
- Multiple users can join a chat room by each entering a unique username
on website load.
- Users can type chat messages to the chat room.
- A notification is sent to all users when a user joins or leaves
the chatroom.

View File

@@ -0,0 +1,51 @@
httpd:
build: ./httpd
links:
- server-john
- server-paul
- server-george
- server-ringo
ports:
- "3000:80"
server-john:
build: ./server
links:
- redis
expose:
- "3000"
environment:
- NAME=John
server-paul:
build: ./server
links:
- redis
expose:
- "3000"
environment:
- NAME=Paul
server-george:
build: ./server
links:
- redis
expose:
- "3000"
environment:
- NAME=George
server-ringo:
build: ./server
links:
- redis
expose:
- "3000"
environment:
- NAME=Ringo
redis:
image: redis:alpine
expose:
- "6379"

View File

@@ -0,0 +1,2 @@
FROM httpd:2.4-alpine
COPY ./httpd.conf /usr/local/apache2/conf/httpd.conf

View File

@@ -0,0 +1,52 @@
Listen 80
ServerName localhost
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule headers_module modules/mod_headers.so
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
LoadModule unixd_module modules/mod_unixd.so
User daemon
Group daemon
ErrorLog /proc/self/fd/2
Header add Set-Cookie "SERVERID=sticky.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED
<Proxy "balancer://nodes_polling">
BalancerMember "http://server-john:3000" route=john
BalancerMember "http://server-paul:3000" route=paul
BalancerMember "http://server-george:3000" route=george
BalancerMember "http://server-ringo:3000" route=ringo
ProxySet stickysession=SERVERID
</Proxy>
<Proxy "balancer://nodes_ws">
BalancerMember "ws://server-john:3000" route=john
BalancerMember "ws://server-paul:3000" route=paul
BalancerMember "ws://server-george:3000" route=george
BalancerMember "ws://server-ringo:3000" route=ringo
ProxySet stickysession=SERVERID
</Proxy>
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule /(.*) balancer://nodes_ws/$1 [P,L]
RewriteCond %{HTTP:Upgrade} !=websocket [NC]
RewriteRule /(.*) balancer://nodes_polling/$1 [P,L]
ProxyTimeout 3

View File

@@ -0,0 +1,15 @@
FROM mhart/alpine-node:6
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Bundle app source
COPY . /usr/src/app
EXPOSE 3000
CMD [ "npm", "start" ]

View File

@@ -0,0 +1,82 @@
// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var redis = require('socket.io-redis');
var port = process.env.PORT || 3000;
var serverName = process.env.NAME || 'Unknown';
io.adapter(redis({ host: 'redis', port: 6379 }));
server.listen(port, function () {
console.log('Server listening at port %d', port);
console.log('Hello, I\'m %s, how can I help?', serverName);
});
// Routing
app.use(express.static(__dirname + '/public'));
// Chatroom
var numUsers = 0;
io.on('connection', function (socket) {
socket.emit('my-name-is', serverName);
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (username) {
if (addedUser) return;
// we store the username in the socket session for this client
socket.username = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
if (addedUser) {
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
}
});
});

View File

@@ -0,0 +1,17 @@
{
"name": "socket.io-chat",
"version": "0.0.0",
"description": "A simple chat client using socket.io",
"main": "index.js",
"author": "Grant Timmerman",
"private": true,
"license": "BSD",
"dependencies": {
"express": "4.13.4",
"socket.io": "^1.7.2",
"socket.io-redis": "^3.0.0"
},
"scripts": {
"start": "node index.js"
}
}

View File

@@ -0,0 +1,28 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.IO Chat Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<ul class="pages">
<li class="chat page">
<div class="chatArea">
<ul class="messages"></ul>
</div>
<input class="inputMessage" placeholder="Type here..."/>
</li>
<li class="login page">
<div class="form">
<h3 class="title">What's your nickname?</h3>
<input class="usernameInput" type="text" maxlength="14" />
</div>
</li>
</ul>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="/main.js"></script>
</body>
</html>

View File

@@ -0,0 +1,286 @@
$(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
// Initialize variables
var $window = $(window);
var $usernameInput = $('.usernameInput'); // Input for username
var $messages = $('.messages'); // Messages area
var $inputMessage = $('.inputMessage'); // Input message input box
var $loginPage = $('.login.page'); // The login page
var $chatPage = $('.chat.page'); // The chatroom page
// Prompt for setting a username
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput.focus();
var socket = io();
function addParticipantsMessage (data) {
var message = '';
if (data.numUsers === 1) {
message += "there's 1 participant";
} else {
message += "there are " + data.numUsers + " participants";
}
log(message);
}
// Sets the client's username
function setUsername () {
username = cleanInput($usernameInput.val().trim());
// If the username is valid
if (username) {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
// Tell the server your username
socket.emit('add user', username);
}
}
// Sends a chat message
function sendMessage () {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
message = cleanInput(message);
// if there is a non-empty message and a socket connection
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
// tell server to execute 'new message' and send along one parameter
socket.emit('new message', message);
}
}
// Log a message
function log (message, options) {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// Adds the visual chat message to the message list
function addChatMessage (data, options) {
// Don't fade the message in if there is an 'X was typing'
var $typingMessages = getTypingMessages(data);
options = options || {};
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// Adds the visual chat typing message
function addChatTyping (data) {
data.typing = true;
data.message = 'is typing';
addChatMessage(data);
}
// Removes the visual chat typing message
function removeChatTyping (data) {
getTypingMessages(data).fadeOut(function () {
$(this).remove();
});
}
// Adds a message element to the messages and scrolls to the bottom
// el - The element to add as a message
// options.fade - If the element should fade-in (default = true)
// options.prepend - If the element should prepend
// all other messages (default = false)
function addMessageElement (el, options) {
var $el = $(el);
// Setup default options
if (!options) {
options = {};
}
if (typeof options.fade === 'undefined') {
options.fade = true;
}
if (typeof options.prepend === 'undefined') {
options.prepend = false;
}
// Apply options
if (options.fade) {
$el.hide().fadeIn(FADE_TIME);
}
if (options.prepend) {
$messages.prepend($el);
} else {
$messages.append($el);
}
$messages[0].scrollTop = $messages[0].scrollHeight;
}
// Prevents input from having injected markup
function cleanInput (input) {
return $('<div/>').text(input).text();
}
// Updates the typing event
function updateTyping () {
if (connected) {
if (!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
// Gets the 'X is typing' messages of a user
function getTypingMessages (data) {
return $('.typing.message').filter(function (i) {
return $(this).data('username') === data.username;
});
}
// Gets the color of a username through our hash function
function getUsernameColor (username) {
// Compute hash code
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// Calculate color
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
}
// Keyboard events
$window.keydown(function (event) {
// Auto-focus the current input when a key is typed
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// When the client hits ENTER on their keyboard
if (event.which === 13) {
if (username) {
sendMessage();
socket.emit('stop typing');
typing = false;
} else {
setUsername();
}
}
});
$inputMessage.on('input', function() {
updateTyping();
});
// Click events
// Focus input when clicking anywhere on login page
$loginPage.click(function () {
$currentInput.focus();
});
// Focus input when clicking on the message input's border
$inputMessage.click(function () {
$inputMessage.focus();
});
// Socket events
// Whenever the server emits 'login', log the login message
socket.on('login', function (data) {
connected = true;
// Display the welcome message
var message = "Welcome to Socket.IO Chat ";
log(message, {
prepend: true
});
addParticipantsMessage(data);
});
// Whenever the server emits 'new message', update the chat body
socket.on('new message', function (data) {
addChatMessage(data);
});
// Whenever the server emits 'user joined', log it in the chat body
socket.on('user joined', function (data) {
log(data.username + ' joined');
addParticipantsMessage(data);
});
// Whenever the server emits 'user left', log it in the chat body
socket.on('user left', function (data) {
log(data.username + ' left');
addParticipantsMessage(data);
removeChatTyping(data);
});
// Whenever the server emits 'typing', show the typing message
socket.on('typing', function (data) {
addChatTyping(data);
});
// Whenever the server emits 'stop typing', kill the typing message
socket.on('stop typing', function (data) {
removeChatTyping(data);
});
socket.on('disconnect', function () {
log('you have been disconnected');
});
socket.on('reconnect', function () {
log('you have been reconnected');
if (username) {
socket.emit('add user', username);
}
});
socket.on('reconnect_error', function () {
log('attempt to reconnect has failed');
});
socket.on('my-name-is', function (serverName) {
log('host is now ' + serverName);
})
});

View File

@@ -0,0 +1,149 @@
/* Fix user-agent */
* {
box-sizing: border-box;
}
html {
font-weight: 300;
-webkit-font-smoothing: antialiased;
}
html, input {
font-family:
"HelveticaNeue-Light",
"Helvetica Neue Light",
"Helvetica Neue",
Helvetica,
Arial,
"Lucida Grande",
sans-serif;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
ul {
list-style: none;
word-wrap: break-word;
}
/* Pages */
.pages {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
.page {
height: 100%;
position: absolute;
width: 100%;
}
/* Login Page */
.login.page {
background-color: #000;
}
.login.page .form {
height: 100px;
margin-top: -100px;
position: absolute;
text-align: center;
top: 50%;
width: 100%;
}
.login.page .form .usernameInput {
background-color: transparent;
border: none;
border-bottom: 2px solid #fff;
outline: none;
padding-bottom: 15px;
text-align: center;
width: 400px;
}
.login.page .title {
font-size: 200%;
}
.login.page .usernameInput {
font-size: 200%;
letter-spacing: 3px;
}
.login.page .title, .login.page .usernameInput {
color: #fff;
font-weight: 100;
}
/* Chat page */
.chat.page {
display: none;
}
/* Font */
.messages {
font-size: 150%;
}
.inputMessage {
font-size: 100%;
}
.log {
color: gray;
font-size: 70%;
margin: 5px;
text-align: center;
}
/* Messages */
.chatArea {
height: 100%;
padding-bottom: 60px;
}
.messages {
height: 100%;
margin: 0;
overflow-y: scroll;
padding: 10px 20px 10px 20px;
}
.message.typing .messageBody {
color: gray;
}
.username {
font-weight: 700;
overflow: hidden;
padding-right: 15px;
text-align: right;
}
/* Input */
.inputMessage {
border: 10px solid #000;
bottom: 0;
height: 60px;
left: 0;
outline: none;
padding-left: 10px;
position: absolute;
right: 0;
width: 100%;
}

View File

@@ -0,0 +1,31 @@
# Socket.IO Chat with nginx & redis
A simple chat demo for socket.io
## How to use
Install [Docker Compose](https://docs.docker.com/compose/install/), then:
```
$ docker-compose up -d
```
And then point your browser to `http://localhost:3000`.
This will start four Socket.IO nodes, behind a nginx proxy which will loadbalance the requests (using the IP of the client, see [ip_hash](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#ip_hash)).
Each node connects to the redis backend, which will enable to broadcast to every client, no matter which node it is currently connected to.
```
# you can kill a given node, the client should reconnect to another node
$ docker-compose stop server-george
```
## Features
- Multiple users can join a chat room by each entering a unique username
on website load.
- Users can type chat messages to the chat room.
- A notification is sent to all users when a user joins or leaves
the chatroom.

View File

@@ -0,0 +1,51 @@
nginx:
build: ./nginx
links:
- server-john
- server-paul
- server-george
- server-ringo
ports:
- "3000:80"
server-john:
build: ./server
links:
- redis
expose:
- "3000"
environment:
- NAME=John
server-paul:
build: ./server
links:
- redis
expose:
- "3000"
environment:
- NAME=Paul
server-george:
build: ./server
links:
- redis
expose:
- "3000"
environment:
- NAME=George
server-ringo:
build: ./server
links:
- redis
expose:
- "3000"
environment:
- NAME=Ringo
redis:
image: redis:alpine
expose:
- "6379"

View File

@@ -0,0 +1,3 @@
FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf

View File

@@ -0,0 +1,35 @@
# Reference: https://www.nginx.com/resources/wiki/start/topics/examples/full/
worker_processes 4;
events {
worker_connections 1024;
}
http {
server {
listen 80;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_pass http://nodes;
# enable WebSockets
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
upstream nodes {
# enable sticky session
ip_hash;
server server-john:3000;
server server-paul:3000;
server server-george:3000;
server server-ringo:3000;
}
}

View File

@@ -0,0 +1,15 @@
FROM mhart/alpine-node:6
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Bundle app source
COPY . /usr/src/app
EXPOSE 3000
CMD [ "npm", "start" ]

View File

@@ -0,0 +1,82 @@
// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var redis = require('socket.io-redis');
var port = process.env.PORT || 3000;
var serverName = process.env.NAME || 'Unknown';
io.adapter(redis({ host: 'redis', port: 6379 }));
server.listen(port, function () {
console.log('Server listening at port %d', port);
console.log('Hello, I\'m %s, how can I help?', serverName);
});
// Routing
app.use(express.static(__dirname + '/public'));
// Chatroom
var numUsers = 0;
io.on('connection', function (socket) {
socket.emit('my-name-is', serverName);
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (username) {
if (addedUser) return;
// we store the username in the socket session for this client
socket.username = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
if (addedUser) {
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
}
});
});

View File

@@ -0,0 +1,17 @@
{
"name": "socket.io-chat",
"version": "0.0.0",
"description": "A simple chat client using socket.io",
"main": "index.js",
"author": "Grant Timmerman",
"private": true,
"license": "BSD",
"dependencies": {
"express": "4.13.4",
"socket.io": "^1.7.2",
"socket.io-redis": "^3.0.0"
},
"scripts": {
"start": "node index.js"
}
}

View File

@@ -0,0 +1,28 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.IO Chat Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<ul class="pages">
<li class="chat page">
<div class="chatArea">
<ul class="messages"></ul>
</div>
<input class="inputMessage" placeholder="Type here..."/>
</li>
<li class="login page">
<div class="form">
<h3 class="title">What's your nickname?</h3>
<input class="usernameInput" type="text" maxlength="14" />
</div>
</li>
</ul>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="/main.js"></script>
</body>
</html>

View File

@@ -0,0 +1,286 @@
$(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
// Initialize variables
var $window = $(window);
var $usernameInput = $('.usernameInput'); // Input for username
var $messages = $('.messages'); // Messages area
var $inputMessage = $('.inputMessage'); // Input message input box
var $loginPage = $('.login.page'); // The login page
var $chatPage = $('.chat.page'); // The chatroom page
// Prompt for setting a username
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput.focus();
var socket = io();
function addParticipantsMessage (data) {
var message = '';
if (data.numUsers === 1) {
message += "there's 1 participant";
} else {
message += "there are " + data.numUsers + " participants";
}
log(message);
}
// Sets the client's username
function setUsername () {
username = cleanInput($usernameInput.val().trim());
// If the username is valid
if (username) {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
// Tell the server your username
socket.emit('add user', username);
}
}
// Sends a chat message
function sendMessage () {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
message = cleanInput(message);
// if there is a non-empty message and a socket connection
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
// tell server to execute 'new message' and send along one parameter
socket.emit('new message', message);
}
}
// Log a message
function log (message, options) {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// Adds the visual chat message to the message list
function addChatMessage (data, options) {
// Don't fade the message in if there is an 'X was typing'
var $typingMessages = getTypingMessages(data);
options = options || {};
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// Adds the visual chat typing message
function addChatTyping (data) {
data.typing = true;
data.message = 'is typing';
addChatMessage(data);
}
// Removes the visual chat typing message
function removeChatTyping (data) {
getTypingMessages(data).fadeOut(function () {
$(this).remove();
});
}
// Adds a message element to the messages and scrolls to the bottom
// el - The element to add as a message
// options.fade - If the element should fade-in (default = true)
// options.prepend - If the element should prepend
// all other messages (default = false)
function addMessageElement (el, options) {
var $el = $(el);
// Setup default options
if (!options) {
options = {};
}
if (typeof options.fade === 'undefined') {
options.fade = true;
}
if (typeof options.prepend === 'undefined') {
options.prepend = false;
}
// Apply options
if (options.fade) {
$el.hide().fadeIn(FADE_TIME);
}
if (options.prepend) {
$messages.prepend($el);
} else {
$messages.append($el);
}
$messages[0].scrollTop = $messages[0].scrollHeight;
}
// Prevents input from having injected markup
function cleanInput (input) {
return $('<div/>').text(input).text();
}
// Updates the typing event
function updateTyping () {
if (connected) {
if (!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
// Gets the 'X is typing' messages of a user
function getTypingMessages (data) {
return $('.typing.message').filter(function (i) {
return $(this).data('username') === data.username;
});
}
// Gets the color of a username through our hash function
function getUsernameColor (username) {
// Compute hash code
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// Calculate color
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
}
// Keyboard events
$window.keydown(function (event) {
// Auto-focus the current input when a key is typed
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// When the client hits ENTER on their keyboard
if (event.which === 13) {
if (username) {
sendMessage();
socket.emit('stop typing');
typing = false;
} else {
setUsername();
}
}
});
$inputMessage.on('input', function() {
updateTyping();
});
// Click events
// Focus input when clicking anywhere on login page
$loginPage.click(function () {
$currentInput.focus();
});
// Focus input when clicking on the message input's border
$inputMessage.click(function () {
$inputMessage.focus();
});
// Socket events
// Whenever the server emits 'login', log the login message
socket.on('login', function (data) {
connected = true;
// Display the welcome message
var message = "Welcome to Socket.IO Chat ";
log(message, {
prepend: true
});
addParticipantsMessage(data);
});
// Whenever the server emits 'new message', update the chat body
socket.on('new message', function (data) {
addChatMessage(data);
});
// Whenever the server emits 'user joined', log it in the chat body
socket.on('user joined', function (data) {
log(data.username + ' joined');
addParticipantsMessage(data);
});
// Whenever the server emits 'user left', log it in the chat body
socket.on('user left', function (data) {
log(data.username + ' left');
addParticipantsMessage(data);
removeChatTyping(data);
});
// Whenever the server emits 'typing', show the typing message
socket.on('typing', function (data) {
addChatTyping(data);
});
// Whenever the server emits 'stop typing', kill the typing message
socket.on('stop typing', function (data) {
removeChatTyping(data);
});
socket.on('disconnect', function () {
log('you have been disconnected');
});
socket.on('reconnect', function () {
log('you have been reconnected');
if (username) {
socket.emit('add user', username);
}
});
socket.on('reconnect_error', function () {
log('attempt to reconnect has failed');
});
socket.on('my-name-is', function (serverName) {
log('host is now ' + serverName);
})
});

View File

@@ -0,0 +1,149 @@
/* Fix user-agent */
* {
box-sizing: border-box;
}
html {
font-weight: 300;
-webkit-font-smoothing: antialiased;
}
html, input {
font-family:
"HelveticaNeue-Light",
"Helvetica Neue Light",
"Helvetica Neue",
Helvetica,
Arial,
"Lucida Grande",
sans-serif;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
ul {
list-style: none;
word-wrap: break-word;
}
/* Pages */
.pages {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
.page {
height: 100%;
position: absolute;
width: 100%;
}
/* Login Page */
.login.page {
background-color: #000;
}
.login.page .form {
height: 100px;
margin-top: -100px;
position: absolute;
text-align: center;
top: 50%;
width: 100%;
}
.login.page .form .usernameInput {
background-color: transparent;
border: none;
border-bottom: 2px solid #fff;
outline: none;
padding-bottom: 15px;
text-align: center;
width: 400px;
}
.login.page .title {
font-size: 200%;
}
.login.page .usernameInput {
font-size: 200%;
letter-spacing: 3px;
}
.login.page .title, .login.page .usernameInput {
color: #fff;
font-weight: 100;
}
/* Chat page */
.chat.page {
display: none;
}
/* Font */
.messages {
font-size: 150%;
}
.inputMessage {
font-size: 100%;
}
.log {
color: gray;
font-size: 70%;
margin: 5px;
text-align: center;
}
/* Messages */
.chatArea {
height: 100%;
padding-bottom: 60px;
}
.messages {
height: 100%;
margin: 0;
overflow-y: scroll;
padding: 10px 20px 10px 20px;
}
.message.typing .messageBody {
color: gray;
}
.username {
font-weight: 700;
overflow: hidden;
padding-right: 15px;
text-align: right;
}
/* Input */
.inputMessage {
border: 10px solid #000;
bottom: 0;
height: 60px;
left: 0;
outline: none;
padding-left: 10px;
position: absolute;
right: 0;
width: 100%;
}

View File

@@ -0,0 +1,50 @@
# Socket.IO custom parsers
Since Socket.IO version 2.0.0, you can provide your custom parser, according to the needs of your application.
Several parsers are showcased here:
- the default one: [socket.io-parser](https://github.com/socketio/socket.io-parser)
- one based on msgpack: [socket.io-msgpack-parser](https://github.com/darrachequesne/socket.io-msgpack-parser)
- one based on native JSON: [socket.io-json-parser](https://github.com/darrachequesne/socket.io-json-parser)
- a custom one based on [schemapack](https://github.com/phretaddin/schemapack)
They are tested with various payloads:
- string: `['1', '2', ... '1000']`
- numeric: `[1, 2, ... 1000]`
- binary: `new Buffer(1000), where buf[i] = i`
## How to use
```
$ npm i && npm start
```
## Results
| bytes / packet | CONNECT packet | string | numeric | binary |
|----------------|----------------|--------|---------|-----------|
| default | 1 | 5903 | 3904 | 43 + 1000 |
| msgpack | 20 | 3919 | 2646 | 1029 |
| JSON | 20 | 5930 | 3931 | 3625 |
| schemapack | 20 | 3895 | 2005 | 1005 |
## Comparison
`default parser`
- supports any serializable datastructure, including Blob and File
- **but** binary payload is encoded as 2 packets
`msgpack`
- the size of payloads containing mostly numeric values will be greatly reduced
- **but** rely on [ArrayBuffer](https://caniuse.com/#feat=typedarrays) in the browser (IE > 9)
`JSON`
- optimized
- **but** does not support binary payloads
`schemapack`
- the most efficient in both speed and size
- **but** you have to provide a schema for each packet

View File

@@ -0,0 +1,21 @@
{
"name": "parsers",
"version": "1.0.0",
"description": "Various socket.io parsers",
"scripts": {
"build": "webpack --config ./support/webpack.config.js",
"start": "npm run build && node ./src/server.js"
},
"author": "Damien Arrachequesne",
"license": "MIT",
"dependencies": {
"component-emitter": "^1.2.1",
"express": "^4.15.2",
"schemapack": "^1.4.2",
"socket.io": "socketio/socket.io",
"socket.io-client": "socketio/socket.io-client",
"socket.io-json-parser": "^1.0.0",
"socket.io-msgpack-parser": "^1.0.0",
"webpack": "^2.4.1"
}
}

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.IO custom parsers</title>
</head>
<body>
<script src="client1.bundle.js"></script>
<script src="client2.bundle.js"></script>
<script src="client3.bundle.js"></script>
<script src="client4.bundle.js"></script>
</body>
</html>

View File

@@ -0,0 +1,8 @@
const socket = require('socket.io-client')('localhost:3001', {});
socket.io.engine.on('data', (data) => console.log('[default]' + ' size= ' + (typeof data === 'string' ? data.length : data.byteLength)));
socket.on('string', (data) => console.log('[default] [string]', data));
socket.on('numeric', (data) => console.log('[default] [numeric]', data));
socket.on('binary', (data) => console.log('[default] [binary]', data));

View File

@@ -0,0 +1,11 @@
const customParser = require('socket.io-msgpack-parser');
const socket = require('socket.io-client')('http://localhost:3002', {
parser: customParser
});
socket.io.engine.on('data', (data) => console.log('[msgpack]' + ' size= ' + (typeof data === 'string' ? data.length : data.byteLength)));
socket.on('string', (data) => console.log('[msgpack] [string]', data));
socket.on('numeric', (data) => console.log('[msgpack] [numeric]', data));
socket.on('binary', (data) => console.log('[msgpack] [binary]', data));

View File

@@ -0,0 +1,11 @@
const customParser = require('socket.io-json-parser');
const socket = require('socket.io-client')('localhost:3003', {
parser: customParser
});
socket.io.engine.on('data', (data) => console.log('[json]' + ' size= ' + (typeof data === 'string' ? data.length : data.byteLength)));
socket.on('string', (data) => console.log('[json] [string]', data));
socket.on('numeric', (data) => console.log('[json] [numeric]', data));
socket.on('binary', (data) => console.log('[json] [binary]', data));

View File

@@ -0,0 +1,11 @@
const customParser = require('./custom-parser');
const socket = require('socket.io-client')('localhost:3004', {
parser: customParser
});
socket.io.engine.on('data', (data) => console.log('[custom]' + ' size= ' + (typeof data === 'string' ? data.length : data.byteLength)));
socket.on('string', (data) => console.log('[custom] [string]', data));
socket.on('numeric', (data) => console.log('[custom] [numeric]', data));
socket.on('binary', (data) => console.log('[custom] [binary]', data));

View File

@@ -0,0 +1,125 @@
const Emitter = require('component-emitter');
const schemapack = require('schemapack');
/**
* Packet types (see https://github.com/socketio/socket.io-protocol)
*/
const TYPES = {
CONNECT: 0,
DISCONNECT: 1,
EVENT: 2,
ACK: 3,
ERROR: 4,
BINARY_EVENT: 5,
BINARY_ACK: 6
};
const stringSchema = schemapack.build({
_id: 'uint8',
data: [ 'string' ],
nsp: 'string'
});
const numericSchema = schemapack.build({
_id: 'uint8',
data: [ 'uint16' ],
nsp: 'string'
});
const binarySchema = schemapack.build({
_id: 'uint8',
data: 'buffer',
nsp: 'string'
});
const errorPacket = {
type: TYPES.ERROR,
data: 'parser error'
};
class Encoder {
encode (packet, callback) {
switch (packet.type) {
case TYPES.EVENT:
return callback([ this.pack(packet) ]);
default:
return callback([ JSON.stringify(packet) ]);
}
}
pack (packet) {
let eventName = packet.data[0];
let flatPacket = {
data: packet.data[1],
nsp: packet.nsp
};
switch (eventName) {
case 'string':
flatPacket._id = 1;
return stringSchema.encode(flatPacket);
case 'numeric':
flatPacket._id = 2;
return numericSchema.encode(flatPacket);
case 'binary':
flatPacket._id = 3;
return binarySchema.encode(flatPacket);
default:
throw new Error('unknown event name: ' + eventName);
}
}
}
class Decoder extends Emitter {
add (obj) {
if (typeof obj === 'string') {
this.parseJSON(obj);
} else {
this.parseBinary(obj);
}
}
parseJSON (obj) {
try {
let decoded = JSON.parse(obj);
this.emit('decoded', decoded);
} catch (e) {
this.emit('decoded', errorPacket);
}
}
parseBinary (obj) {
let view = new Uint8Array(obj);
let packetId = view[0];
try {
let packet = {
type: TYPES.EVENT
};
let decoded;
switch (packetId) {
case 1:
decoded = stringSchema.decode(obj);
packet.data = [ 'string', decoded.data ];
packet.nsp = decoded.nsp;
break;
case 2:
decoded = numericSchema.decode(obj);
packet.data = [ 'numeric', decoded.data ];
packet.nsp = decoded.nsp;
break;
case 3:
decoded = binarySchema.decode(obj);
packet.data = [ 'binary', decoded.data.buffer ];
packet.nsp = decoded.nsp;
break;
default:
throw new Error('unknown type');
}
this.emit('decoded', packet);
} catch (e) {
this.emit('decoded', errorPacket);
}
}
destroy () {}
}
exports.Encoder = Encoder;
exports.Decoder = Decoder;

View File

@@ -0,0 +1,55 @@
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const path = require('path');
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, '../public')));
server.listen(port, () => console.log('>>> http://localhost:' + port));
const io = require('socket.io');
const msgpackParser = require('socket.io-msgpack-parser');
const jsonParser = require('socket.io-json-parser');
const customParser = require('./custom-parser');
let server1 = io(3001, {});
let server2 = io(3002, {
parser: msgpackParser
});
let server3 = io(3003, {
parser: jsonParser
});
let server4 = io(3004, {
parser: customParser
});
let string = [];
let numeric = [];
let binary = new Buffer(1e3);
for (var i = 0; i < 1e3; i++) {
string.push('' + i);
numeric.push(i);
binary[i] = i;
}
server1.on('connect', onConnect(1000));
server2.on('connect', onConnect(2000));
server3.on('connect', onConnect(3000));
server4.on('connect', onConnect(4000));
function onConnect (delay) {
return function (socket) {
console.log('connect ' + socket.id);
setTimeout(() => {
socket.emit('string', string);
socket.emit('numeric', numeric);
socket.emit('binary', binary);
}, delay);
socket.on('disconnect', () => console.log('disconnect ' + socket.id));
};
}

View File

@@ -0,0 +1,15 @@
const path = require('path');
module.exports = {
entry: {
client1: './src/client1.js',
client2: './src/client2.js',
client3: './src/client3.js',
client4: './src/client4.js'
},
output: {
path: path.resolve(__dirname, '../public'),
filename: '[name].bundle.js'
}
};

View File

@@ -1,74 +0,0 @@
/**
* Module dependencies.
*/
var express = require('express')
, stylus = require('stylus')
, nib = require('nib')
, sio = require('../../lib/socket.io')
, irc = require('./irc');
/**
* App.
*/
var app = express.createServer();
/**
* App configuration.
*/
app.configure(function () {
app.use(stylus.middleware({ src: __dirname + '/public', compile: compile }))
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname);
app.set('view engine', 'jade');
function compile (str, path) {
return stylus(str)
.set('filename', path)
.use(nib());
};
});
/**
* App routes.
*/
app.get('/', function (req, res) {
res.render('index', { layout: false });
});
/**
* App listen.
*/
app.listen(3000, function () {
var addr = app.address();
console.log(' app listening on http://' + addr.address + ':' + addr.port);
});
/**
* Socket.IO server
*/
var io = sio.listen(app)
/**
* Connect to IRC.
*/
var client = new irc.Client('irc.freenode.net', 6667);
client.connect('socketio\\test\\' + String(Math.random()).substr(-3));
client.on('001', function () {
this.send('JOIN', '#node.js');
});
client.on('PART', function (prefix) {
io.sockets.emit('announcement', irc.user(prefix) + ' left the channel');
});
client.on('JOIN', function (prefix) {
io.sockets.emit('announcement', irc.user(prefix) + ' joined the channel');
});
client.on('PRIVMSG', function (prefix, channel, text) {
io.sockets.emit('irc message', irc.user(prefix), text);
});

View File

@@ -1,28 +0,0 @@
doctype 5
html
head
link(href='/stylesheets/style.css', rel='stylesheet')
script(src='http://code.jquery.com/jquery-1.6.1.min.js')
script(src='/socket.io/socket.io.js')
script
var socket = io.connect();
socket.on('connect', function () {
$('#irc').addClass('connected');
});
socket.on('announcement', function (msg) {
$('#messages').append($('<p>').append($('<em>').text(msg)));
$('#messages').get(0).scrollTop = 10000000;
});
socket.on('irc message', function (user, msg) {
$('#messages').append($('<p>').append($('<b>').text(user), msg));
$('#messages').get(0).scrollTop = 10000000;
});
body
h2 Node.JS IRC
#irc
#connecting
.wrap Connecting to socket.io server
#messages

View File

@@ -1,164 +0,0 @@
/**
* From https://github.com/felixge/nodelog/
*/
var sys = require('util');
var tcp = require('net');
var irc = exports;
function bind(fn, scope) {
var bindArgs = Array.prototype.slice.call(arguments);
bindArgs.shift();
bindArgs.shift();
return function() {
var args = Array.prototype.slice.call(arguments);
fn.apply(scope, bindArgs.concat(args));
};
}
function each(set, iterator) {
for (var i = 0; i < set.length; i++) {
var r = iterator(set[i], i);
if (r === false) {
return;
}
}
}
var Client = irc.Client = function(host, port) {
this.host = host || 'localhost';
this.port = port || 6667;
this.connection = null;
this.buffer = '';
this.encoding = 'utf8';
this.timeout = 10 * 60 * 60 * 1000;
this.nick = null;
this.user = null;
this.real = null;
}
sys.inherits(Client, process.EventEmitter);
Client.prototype.connect = function(nick, user, real) {
var connection = tcp.createConnection(this.port, this.host);
connection.setEncoding(this.encoding);
connection.setTimeout(this.timeout);
connection.addListener('connect', bind(this.onConnect, this));
connection.addListener('data', bind(this.onReceive, this));
connection.addListener('end', bind(this.onEof, this));
connection.addListener('timeout', bind(this.onTimeout, this));
connection.addListener('close', bind(this.onClose, this));
this.nick = nick;
this.user = user || 'guest';
this.real = real || 'Guest';
this.connection = connection;
};
Client.prototype.disconnect = function(why) {
if (this.connection.readyState !== 'closed') {
this.connection.close();
sys.puts('disconnected (reason: '+why+')');
this.emit('DISCONNECT', why);
}
};
Client.prototype.send = function(arg1) {
if (this.connection.readyState !== 'open') {
return this.disconnect('cannot send with readyState: '+this.connection.readyState);
}
var message = [];
for (var i = 0; i< arguments.length; i++) {
if (arguments[i]) {
message.push(arguments[i]);
}
}
message = message.join(' ');
sys.puts('> '+message);
message = message + "\r\n";
this.connection.write(message, this.encoding);
};
Client.prototype.parse = function(message) {
var match = message.match(/(?:(:[^\s]+) )?([^\s]+) (.+)/);
var parsed = {
prefix: match[1],
command: match[2]
};
var params = match[3].match(/(.*?) ?:(.*)/);
if (params) {
// Params before :
params[1] = (params[1])
? params[1].split(' ')
: [];
// Rest after :
params[2] = params[2]
? [params[2]]
: [];
params = params[1].concat(params[2]);
} else {
params = match[3].split(' ');
}
parsed.params = params;
return parsed;
};
Client.prototype.onConnect = function() {
this.send('NICK', this.nick);
this.send('USER', this.user, '0', '*', ':'+this.real);
};
Client.prototype.onReceive = function(chunk) {
this.buffer = this.buffer + chunk;
while (this.buffer) {
var offset = this.buffer.indexOf("\r\n");
if (offset < 0) {
return;
}
var message = this.buffer.substr(0, offset);
this.buffer = this.buffer.substr(offset + 2);
sys.puts('< '+message);
message = this.parse(message);
this.emit.apply(this, [message.command, message.prefix].concat(message.params));
if (message !== false) {
this.onMessage(message);
}
}
};
Client.prototype.onMessage = function(message) {
switch (message.command) {
case 'PING':
this.send('PONG', ':'+message.params[0]);
break;
}
};
Client.prototype.onEof = function() {
this.disconnect('eof');
};
Client.prototype.onTimeout = function() {
this.disconnect('timeout');
};
Client.prototype.onClose = function() {
this.disconnect('close');
};
exports.user = function(prefix) {
return prefix.match(/:([^!]+)!/)[1]
};

View File

@@ -1,10 +0,0 @@
{
"name": "socket.io-irc"
, "version": "0.0.1"
, "dependencies": {
"express": "2.5.5"
, "jade": "0.16.4"
, "stylus": "0.19.0"
, "nib": "0.2.0"
}
}

View File

@@ -1,69 +0,0 @@
@import 'nib'
h2
font bold 18px Helvetica Neue, Arial
#irc, #messages
width 600px
#irc
position relative
border 1px solid #ccc
#connecting
position absolute
height 410px
z-index 100
left 0
top 0
background #fff
text-align center
width 600px
font 15px Georgia
color #666
display block
.wrap
padding-top 150px
.connected
#connecting
display none
#messages
height 380px
background #eee
overflow auto
overflow-x hidden
overflow-y auto
&::-webkit-scrollbar
width 6px
height 6px
&::-webkit-scrollbar-button:start:decrement, ::-webkit-scrollbar-button:end:increment
display block
height 10px
&::-webkit-scrollbar-button:vertical:increment
background-color #fff
&::-webkit-scrollbar-track-piece
background-color #fff
-webkit-border-radius 3px
&::-webkit-scrollbar-thumb:vertical
height 50px
background-color #ccc
-webkit-border-radius 3px
&::-webkit-scrollbar-thumb:horizontal
width 50px
background-color #fff
-webkit-border-radius 3px
em
text-shadow 0 1px 0 #fff
color #999
p
padding 0
margin 0
font 12px Helvetica, Arial
padding 5px 10px
b
display inline-block
padding-right 10px
p:nth-child(even)
background #fafafa

View File

@@ -0,0 +1,18 @@
# Socket.IO WebPack build
A sample Webpack build for the server.
## How to use
```
$ npm i
$ npm run build
$ npm start
```
**Note:**
- the `bufferutil` and `utf-8-validate` are optional dependencies from `ws`, compiled from native code, which are meant to improve performance ([ref](https://github.com/websockets/ws#opt-in-for-performance)). You can also omit them, as they have their JS fallback, and ignore the WebPack warning.
- the server is initiated with `serveClient` set to `false`, so it will not serve the client file.

View File

@@ -0,0 +1,15 @@
const server = require('http').createServer();
const io = require('socket.io')(server, {
// serveClient: false // do not serve the client file, in that case the brfs loader is not needed
});
const port = process.env.PORT || 3000;
io.on('connect', onConnect);
server.listen(port, () => console.log('server listening on port ' + port));
function onConnect(socket){
console.log('connect ' + socket.id);
socket.on('disconnect', () => console.log('disconnect ' + socket.id));
}

View File

@@ -0,0 +1,23 @@
{
"name": "webpack-build-server",
"version": "1.0.0",
"description": "A sample Webpack build (for the server)",
"scripts": {
"start": "node dist/server.js",
"build": "webpack --config ./support/webpack.config.js"
},
"author": "Damien Arrachequesne",
"license": "MIT",
"dependencies": {
"brfs": "^1.4.3",
"bufferutil": "^1.3.0",
"socket.io": "^1.7.2",
"transform-loader": "^0.2.3",
"utf-8-validate": "^2.0.0"
},
"devDependencies": {
"json-loader": "^0.5.4",
"null-loader": "^0.1.1",
"webpack": "^1.14.0"
}
}

View File

@@ -0,0 +1,25 @@
module.exports = {
entry: './lib/index.js',
target: 'node',
output: {
path: './dist',
filename: 'server.js'
},
module: {
loaders: [
{
test: /(\.md|\.map)$/,
loader: 'null'
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.js$/,
loader: "transform-loader?brfs"
}
]
}
};

View File

@@ -0,0 +1,20 @@
# Socket.IO WebPack build
A sample Webpack build for the browser.
## How to use
```
$ npm i
$ npm run build-all
```
There are two WebPack configuration:
- the minimal configuration, just bundling the application and its dependencies. The `app.js` file in the `dist` folder is the result of that build.
- a slimmer one, where:
- the JSON polyfill needed for IE6/IE7 support has been removed.
- the `debug` calls and import have been removed (the [debug](https://github.com/visionmedia/debug) library is included in the build by default).
- the source has been uglified (dropping IE8 support), and an associated SourceMap has been generated.

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.IO WebPack Example</title>
</head>
<body>
<!-- <script src="dist/app.js"></script> -->
<script src="dist/app.slim.js"></script>
</body>
</html>

View File

@@ -0,0 +1,10 @@
var socket = require('socket.io-client')('http://localhost:3000');
console.log('init');
socket.on('connect', onConnect);
function onConnect(){
console.log('connect ' + socket.id);
}

View File

@@ -0,0 +1,19 @@
{
"name": "webpack-build",
"version": "1.0.0",
"description": "A sample Webpack build",
"scripts": {
"build": "webpack --config ./support/webpack.config.js",
"build-slim": "webpack --config ./support/webpack.config.slim.js",
"build-all": "npm run build && npm run build-slim"
},
"author": "Damien Arrachequesne",
"license": "MIT",
"dependencies": {
"socket.io-client": "^1.7.2"
},
"devDependencies": {
"strip-loader": "^0.1.2",
"webpack": "^1.14.0"
}
}

View File

@@ -0,0 +1,2 @@
module.exports = function () { return function () {}; };

View File

@@ -0,0 +1,8 @@
module.exports = {
entry: './lib/index.js',
output: {
path: './dist',
filename: 'app.js'
},
};

View File

@@ -0,0 +1,35 @@
var webpack = require('webpack');
module.exports = {
entry: './lib/index.js',
output: {
path: './dist',
filename: 'app.slim.js'
},
externals: {
// replace JSON polyfill (IE6/IE7) with global JSON object
json3: 'JSON'
},
// generate sourcemap
devtool: 'source-map',
plugins: [
// replace require('debug')() with an noop function
new webpack.NormalModuleReplacementPlugin(/debug/, process.cwd() + '/support/noop.js'),
// use uglifyJS (IE9+ support)
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
],
module: {
loaders: [
{
// strip `debug()` calls
test: /\.js$/,
loader: 'strip-loader?strip[]=debug'
}
]
}
};

View File

@@ -0,0 +1,17 @@
# Socket.IO Collaborative Whiteboard
A simple collaborative whiteboard for socket.io
## How to use
```
$ npm i && npm start
```
And point your browser to `http://localhost:3000`. Optionally, specify
a port by supplying the `PORT` env variable.
## Features
- draw on the whiteboard and all other users will see you drawings live

View File

@@ -0,0 +1,16 @@
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
function onConnection(socket){
socket.on('drawing', (data) => socket.broadcast.emit('drawing', data));
}
io.on('connection', onConnection);
http.listen(port, () => console.log('listening on port ' + port));

View File

@@ -0,0 +1,19 @@
{
"name": "whiteboard",
"version": "1.0.0",
"description": "A simple collaborative whiteboard using socket.io",
"main": "index.js",
"keywords": [
"socket.io",
"whiteboard"
],
"dependencies": {
"express": "4.9.x",
"socket.io": "latest"
},
"scripts": {
"start": "node index"
},
"author": "Damien Arrachequesne",
"license": "MIT"
}

View File

@@ -0,0 +1,23 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.IO whiteboard</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas class="whiteboard" ></canvas>
<div class="colors">
<div class="color black"></div>
<div class="color red"></div>
<div class="color green"></div>
<div class="color blue"></div>
<div class="color yellow"></div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script src="/main.js"></script>
</body>
</html>

View File

@@ -0,0 +1,100 @@
'use strict';
(function() {
var socket = io();
var canvas = document.getElementsByClassName('whiteboard')[0];
var colors = document.getElementsByClassName('color');
var context = canvas.getContext('2d');
var current = {
color: 'black'
};
var drawing = false;
canvas.addEventListener('mousedown', onMouseDown, false);
canvas.addEventListener('mouseup', onMouseUp, false);
canvas.addEventListener('mouseout', onMouseUp, false);
canvas.addEventListener('mousemove', throttle(onMouseMove, 10), false);
for (var i = 0; i < colors.length; i++){
colors[i].addEventListener('click', onColorUpdate, false);
}
socket.on('drawing', onDrawingEvent);
window.addEventListener('resize', onResize, false);
onResize();
function drawLine(x0, y0, x1, y1, color, emit){
context.beginPath();
context.moveTo(x0, y0);
context.lineTo(x1, y1);
context.strokeStyle = color;
context.lineWidth = 2;
context.stroke();
context.closePath();
if (!emit) { return; }
var w = canvas.width;
var h = canvas.height;
socket.emit('drawing', {
x0: x0 / w,
y0: y0 / h,
x1: x1 / w,
y1: y1 / h,
color: color
});
}
function onMouseDown(e){
drawing = true;
current.x = e.clientX;
current.y = e.clientY;
}
function onMouseUp(e){
if (!drawing) { return; }
drawing = false;
drawLine(current.x, current.y, e.clientX, e.clientY, current.color, true);
}
function onMouseMove(e){
if (!drawing) { return; }
drawLine(current.x, current.y, e.clientX, e.clientY, current.color, true);
current.x = e.clientX;
current.y = e.clientY;
}
function onColorUpdate(e){
current.color = e.target.className.split(' ')[1];
}
// limit the number of events per second
function throttle(callback, delay) {
var previousCall = new Date().getTime();
return function() {
var time = new Date().getTime();
if ((time - previousCall) >= delay) {
previousCall = time;
callback.apply(null, arguments);
}
};
}
function onDrawingEvent(data){
var w = canvas.width;
var h = canvas.height;
drawLine(data.x0 * w, data.y0 * h, data.x1 * w, data.y1 * h, data.color);
}
// make the canvas fill its parent
function onResize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
})();

View File

@@ -0,0 +1,44 @@
/**
* Fix user-agent
*/
* {
box-sizing: border-box;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
/**
* Canvas
*/
.whiteboard {
height: 100%;
width: 100%;
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
}
.colors {
position: fixed;
}
.color {
display: inline-block;
height: 48px;
width: 48px;
}
.color.black { background-color: black; }
.color.red { background-color: red; }
.color.green { background-color: green; }
.color.blue { background-color: blue; }
.color.yellow { background-color: yellow; }

69
gulpfile.js Normal file
View File

@@ -0,0 +1,69 @@
const gulp = require('gulp');
const mocha = require('gulp-mocha');
const babel = require("gulp-babel");
const istanbul = require('gulp-istanbul');
const help = require('gulp-task-listing');
const del = require('del');
gulp.task('help', help);
gulp.task('default', ['transpile']);
const TRANSPILE_DEST_DIR = './dist';
// By default, individual js files are transformed by babel and exported to /dist
gulp.task('transpile', function () {
return gulp.src("lib/*.js")
.pipe(babel({ "presets": ["es2015"] }))
.pipe(gulp.dest(TRANSPILE_DEST_DIR));
});
gulp.task('clean', function () {
return del([TRANSPILE_DEST_DIR]);
})
gulp.task('test', ['transpile'], function(){
return gulp.src('test/socket.io.js', {read: false})
.pipe(mocha({
slow: 200,
reporter: 'spec',
bail: true,
timeout: 10000
}))
.once('error', function (err) {
console.error(err.stack);
process.exit(1);
})
.once('end', function () {
process.exit();
});
});
gulp.task('set-compat-node-env', function() {
process.env.TEST_VERSION = 'compat';
});
gulp.task('test-compat', ['set-compat-node-env', 'test']);
gulp.task('istanbul-pre-test', function () {
return gulp.src(['lib/**/*.js'])
// Covering files
.pipe(istanbul())
// Force `require` to return covered files
.pipe(istanbul.hookRequire());
});
gulp.task('test-cov', ['istanbul-pre-test'], function(){
return gulp.src('test/socket.io.js', {read: false})
.pipe(mocha({
reporter: 'dot'
}))
.pipe(istanbul.writeReports())
.once('error', function (err){
console.error(err.stack);
process.exit(1);
})
.once('end', function (){
process.exit();
});
});

View File

@@ -1,8 +0,0 @@
/*!
* socket.io-node
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
module.exports = require('./lib/socket.io');

252
lib/client.js Normal file
View File

@@ -0,0 +1,252 @@
/**
* Module dependencies.
*/
var parser = require('socket.io-parser');
var debug = require('debug')('socket.io:client');
var url = require('url');
/**
* Module exports.
*/
module.exports = Client;
/**
* Client constructor.
*
* @param {Server} server instance
* @param {Socket} conn
* @api private
*/
function Client(server, conn){
this.server = server;
this.conn = conn;
this.encoder = server.encoder;
this.decoder = new server.parser.Decoder();
this.id = conn.id;
this.request = conn.request;
this.setup();
this.sockets = {};
this.nsps = {};
this.connectBuffer = [];
}
/**
* Sets up event listeners.
*
* @api private
*/
Client.prototype.setup = function(){
this.onclose = this.onclose.bind(this);
this.ondata = this.ondata.bind(this);
this.onerror = this.onerror.bind(this);
this.ondecoded = this.ondecoded.bind(this);
this.decoder.on('decoded', this.ondecoded);
this.conn.on('data', this.ondata);
this.conn.on('error', this.onerror);
this.conn.on('close', this.onclose);
};
/**
* Connects a client to a namespace.
*
* @param {String} name namespace
* @api private
*/
Client.prototype.connect = function(name, query){
debug('connecting to namespace %s', name);
var nsp = this.server.nsps[name];
if (!nsp) {
this.packet({ type: parser.ERROR, nsp: name, data : 'Invalid namespace'});
return;
}
if ('/' != name && !this.nsps['/']) {
this.connectBuffer.push(name);
return;
}
var self = this;
var socket = nsp.add(this, query, function(){
self.sockets[socket.id] = socket;
self.nsps[nsp.name] = socket;
if ('/' == nsp.name && self.connectBuffer.length > 0) {
self.connectBuffer.forEach(self.connect, self);
self.connectBuffer = [];
}
});
};
/**
* Disconnects from all namespaces and closes transport.
*
* @api private
*/
Client.prototype.disconnect = function(){
for (var id in this.sockets) {
if (this.sockets.hasOwnProperty(id)) {
this.sockets[id].disconnect();
}
}
this.sockets = {};
this.close();
};
/**
* Removes a socket. Called by each `Socket`.
*
* @api private
*/
Client.prototype.remove = function(socket){
if (this.sockets.hasOwnProperty(socket.id)) {
var nsp = this.sockets[socket.id].nsp.name;
delete this.sockets[socket.id];
delete this.nsps[nsp];
} else {
debug('ignoring remove for %s', socket.id);
}
};
/**
* Closes the underlying connection.
*
* @api private
*/
Client.prototype.close = function(){
if ('open' == this.conn.readyState) {
debug('forcing transport close');
this.conn.close();
this.onclose('forced server close');
}
};
/**
* Writes a packet to the transport.
*
* @param {Object} packet object
* @param {Object} opts
* @api private
*/
Client.prototype.packet = function(packet, opts){
opts = opts || {};
var self = this;
// this writes to the actual connection
function writeToEngine(encodedPackets) {
if (opts.volatile && !self.conn.transport.writable) return;
for (var i = 0; i < encodedPackets.length; i++) {
self.conn.write(encodedPackets[i], { compress: opts.compress });
}
}
if ('open' == this.conn.readyState) {
debug('writing packet %j', packet);
if (!opts.preEncoded) { // not broadcasting, need to encode
this.encoder.encode(packet, writeToEngine); // encode, then write results to engine
} else { // a broadcast pre-encodes a packet
writeToEngine(packet);
}
} else {
debug('ignoring packet write %j', packet);
}
};
/**
* Called with incoming transport data.
*
* @api private
*/
Client.prototype.ondata = function(data){
// try/catch is needed for protocol violations (GH-1880)
try {
this.decoder.add(data);
} catch(e) {
this.onerror(e);
}
};
/**
* Called when parser fully decodes a packet.
*
* @api private
*/
Client.prototype.ondecoded = function(packet) {
if (parser.CONNECT == packet.type) {
this.connect(url.parse(packet.nsp).pathname, url.parse(packet.nsp, true).query);
} else {
var socket = this.nsps[packet.nsp];
if (socket) {
process.nextTick(function() {
socket.onpacket(packet);
});
} else {
debug('no socket for namespace %s', packet.nsp);
}
}
};
/**
* Handles an error.
*
* @param {Object} err object
* @api private
*/
Client.prototype.onerror = function(err){
for (var id in this.sockets) {
if (this.sockets.hasOwnProperty(id)) {
this.sockets[id].onerror(err);
}
}
this.conn.close();
};
/**
* Called upon transport close.
*
* @param {String} reason
* @api private
*/
Client.prototype.onclose = function(reason){
debug('client close with reason %s', reason);
// ignore a potential subsequent `close` event
this.destroy();
// `nsps` and `sockets` are cleaned up seamlessly
for (var id in this.sockets) {
if (this.sockets.hasOwnProperty(id)) {
this.sockets[id].onclose(reason);
}
}
this.sockets = {};
this.decoder.destroy(); // clean up decoder
};
/**
* Cleans up event listeners.
*
* @api private
*/
Client.prototype.destroy = function(){
this.conn.removeListener('data', this.ondata);
this.conn.removeListener('error', this.onerror);
this.conn.removeListener('close', this.onclose);
this.decoder.removeListener('decoded', this.ondecoded);
};

461
lib/index.js Normal file
View File

@@ -0,0 +1,461 @@
/**
* Module dependencies.
*/
var http = require('http');
var read = require('fs').readFileSync;
var path = require('path');
var exists = require('fs').existsSync;
var engine = require('engine.io');
var client = require('socket.io-client');
var clientVersion = require('socket.io-client/package').version;
var Client = require('./client');
var Emitter = require('events').EventEmitter;
var Namespace = require('./namespace');
var Adapter = require('socket.io-adapter');
var parser = require('socket.io-parser');
var debug = require('debug')('socket.io:server');
var url = require('url');
/**
* Module exports.
*/
module.exports = Server;
/**
* Socket.IO client source.
*/
var clientSource = undefined;
var clientSourceMap = undefined;
/**
* Server constructor.
*
* @param {http.Server|Number|Object} srv http server, port or options
* @param {Object} [opts]
* @api public
*/
function Server(srv, opts){
if (!(this instanceof Server)) return new Server(srv, opts);
if ('object' == typeof srv && srv instanceof Object && !srv.listen) {
opts = srv;
srv = null;
}
opts = opts || {};
this.nsps = {};
this.path(opts.path || '/socket.io');
this.serveClient(false !== opts.serveClient);
this.parser = opts.parser || parser;
this.encoder = new this.parser.Encoder();
this.adapter(opts.adapter || Adapter);
this.origins(opts.origins || '*:*');
this.sockets = this.of('/');
if (srv) this.attach(srv, opts);
}
/**
* Server request verification function, that checks for allowed origins
*
* @param {http.IncomingMessage} req request
* @param {Function} fn callback to be called with the result: `fn(err, success)`
*/
Server.prototype.checkRequest = function(req, fn) {
var origin = req.headers.origin || req.headers.referer;
// file:// URLs produce a null Origin which can't be authorized via echo-back
if ('null' == origin || null == origin) origin = '*';
if (!!origin && typeof(this._origins) == 'function') return this._origins(origin, fn);
if (this._origins.indexOf('*:*') !== -1) return fn(null, true);
if (origin) {
try {
var parts = url.parse(origin);
var defaultPort = 'https:' == parts.protocol ? 443 : 80;
parts.port = parts.port != null
? parts.port
: defaultPort;
var ok =
~this._origins.indexOf(parts.hostname + ':' + parts.port) ||
~this._origins.indexOf(parts.hostname + ':*') ||
~this._origins.indexOf('*:' + parts.port);
return fn(null, !!ok);
} catch (ex) {
}
}
fn(null, false);
};
/**
* Sets/gets whether client code is being served.
*
* @param {Boolean} v whether to serve client code
* @return {Server|Boolean} self when setting or value when getting
* @api public
*/
Server.prototype.serveClient = function(v){
if (!arguments.length) return this._serveClient;
this._serveClient = v;
var resolvePath = function(file){
var filepath = path.resolve(__dirname, './../../', file);
if (exists(filepath)) {
return filepath;
}
return require.resolve(file);
};
if (v && !clientSource) {
clientSource = read(resolvePath( 'socket.io-client/dist/socket.io.js'), 'utf-8');
try {
clientSourceMap = read(resolvePath( 'socket.io-client/dist/socket.io.js.map'), 'utf-8');
} catch(err) {
debug('could not load sourcemap file');
}
}
return this;
};
/**
* Old settings for backwards compatibility
*/
var oldSettings = {
"transports": "transports",
"heartbeat timeout": "pingTimeout",
"heartbeat interval": "pingInterval",
"destroy buffer size": "maxHttpBufferSize"
};
/**
* Backwards compatibility.
*
* @api public
*/
Server.prototype.set = function(key, val){
if ('authorization' == key && val) {
this.use(function(socket, next) {
val(socket.request, function(err, authorized) {
if (err) return next(new Error(err));
if (!authorized) return next(new Error('Not authorized'));
next();
});
});
} else if ('origins' == key && val) {
this.origins(val);
} else if ('resource' == key) {
this.path(val);
} else if (oldSettings[key] && this.eio[oldSettings[key]]) {
this.eio[oldSettings[key]] = val;
} else {
console.error('Option %s is not valid. Please refer to the README.', key);
}
return this;
};
/**
* Sets the client serving path.
*
* @param {String} v pathname
* @return {Server|String} self when setting or value when getting
* @api public
*/
Server.prototype.path = function(v){
if (!arguments.length) return this._path;
this._path = v.replace(/\/$/, '');
return this;
};
/**
* Sets the adapter for rooms.
*
* @param {Adapter} v pathname
* @return {Server|Adapter} self when setting or value when getting
* @api public
*/
Server.prototype.adapter = function(v){
if (!arguments.length) return this._adapter;
this._adapter = v;
for (var i in this.nsps) {
if (this.nsps.hasOwnProperty(i)) {
this.nsps[i].initAdapter();
}
}
return this;
};
/**
* Sets the allowed origins for requests.
*
* @param {String} v origins
* @return {Server|Adapter} self when setting or value when getting
* @api public
*/
Server.prototype.origins = function(v){
if (!arguments.length) return this._origins;
this._origins = v;
return this;
};
/**
* Attaches socket.io to a server or port.
*
* @param {http.Server|Number} server or port
* @param {Object} options passed to engine.io
* @return {Server} self
* @api public
*/
Server.prototype.listen =
Server.prototype.attach = function(srv, opts){
if ('function' == typeof srv) {
var msg = 'You are trying to attach socket.io to an express ' +
'request handler function. Please pass a http.Server instance.';
throw new Error(msg);
}
// handle a port as a string
if (Number(srv) == srv) {
srv = Number(srv);
}
if ('number' == typeof srv) {
debug('creating http server and binding to %d', srv);
var port = srv;
srv = http.Server(function(req, res){
res.writeHead(404);
res.end();
});
srv.listen(port);
}
// set engine.io path to `/socket.io`
opts = opts || {};
opts.path = opts.path || this.path();
// set origins verification
opts.allowRequest = opts.allowRequest || this.checkRequest.bind(this);
var self = this;
var connectPacket = { type: parser.CONNECT, nsp: '/' };
this.encoder.encode(connectPacket, function (encodedPacket){
// the CONNECT packet will be merged with Engine.IO handshake,
// to reduce the number of round trips
opts.initialPacket = encodedPacket;
// initialize engine
debug('creating engine.io instance with opts %j', opts);
self.eio = engine.attach(srv, opts);
// attach static file serving
if (self._serveClient) self.attachServe(srv);
// Export http server
self.httpServer = srv;
// bind to engine events
self.bind(self.eio);
});
return this;
};
/**
* Attaches the static file serving.
*
* @param {Function|http.Server} srv http server
* @api private
*/
Server.prototype.attachServe = function(srv){
debug('attaching client serving req handler');
var url = this._path + '/socket.io.js';
var urlMap = this._path + '/socket.io.js.map';
var evs = srv.listeners('request').slice(0);
var self = this;
srv.removeAllListeners('request');
srv.on('request', function(req, res) {
if (0 === req.url.indexOf(urlMap)) {
self.serveMap(req, res);
} else if (0 === req.url.indexOf(url)) {
self.serve(req, res);
} else {
for (var i = 0; i < evs.length; i++) {
evs[i].call(srv, req, res);
}
}
});
};
/**
* Handles a request serving `/socket.io.js`
*
* @param {http.Request} req
* @param {http.Response} res
* @api private
*/
Server.prototype.serve = function(req, res){
// Per the standard, ETags must be quoted:
// https://tools.ietf.org/html/rfc7232#section-2.3
var expectedEtag = '"' + clientVersion + '"';
var etag = req.headers['if-none-match'];
if (etag) {
if (expectedEtag == etag) {
debug('serve client 304');
res.writeHead(304);
res.end();
return;
}
}
debug('serve client source');
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('ETag', expectedEtag);
res.writeHead(200);
res.end(clientSource);
};
/**
* Handles a request serving `/socket.io.js.map`
*
* @param {http.Request} req
* @param {http.Response} res
* @api private
*/
Server.prototype.serveMap = function(req, res){
// Per the standard, ETags must be quoted:
// https://tools.ietf.org/html/rfc7232#section-2.3
var expectedEtag = '"' + clientVersion + '"';
var etag = req.headers['if-none-match'];
if (etag) {
if (expectedEtag == etag) {
debug('serve client 304');
res.writeHead(304);
res.end();
return;
}
}
debug('serve client sourcemap');
res.setHeader('Content-Type', 'application/json');
res.setHeader('ETag', expectedEtag);
res.writeHead(200);
res.end(clientSourceMap);
};
/**
* Binds socket.io to an engine.io instance.
*
* @param {engine.Server} engine engine.io (or compatible) server
* @return {Server} self
* @api public
*/
Server.prototype.bind = function(engine){
this.engine = engine;
this.engine.on('connection', this.onconnection.bind(this));
return this;
};
/**
* Called with each incoming transport connection.
*
* @param {engine.Socket} conn
* @return {Server} self
* @api public
*/
Server.prototype.onconnection = function(conn){
debug('incoming connection with id %s', conn.id);
var client = new Client(this, conn);
client.connect('/');
return this;
};
/**
* Looks up a namespace.
*
* @param {String} name nsp name
* @param {Function} [fn] optional, nsp `connection` ev handler
* @api public
*/
Server.prototype.of = function(name, fn){
if (String(name)[0] !== '/') name = '/' + name;
var nsp = this.nsps[name];
if (!nsp) {
debug('initializing namespace %s', name);
nsp = new Namespace(this, name);
this.nsps[name] = nsp;
}
if (fn) nsp.on('connect', fn);
return nsp;
};
/**
* Closes server connection
*
* @param {Function} [fn] optional, called as `fn([err])` on error OR all conns closed
* @api public
*/
Server.prototype.close = function(fn){
for (var id in this.nsps['/'].sockets) {
if (this.nsps['/'].sockets.hasOwnProperty(id)) {
this.nsps['/'].sockets[id].onclose();
}
}
this.engine.close();
if (this.httpServer) {
this.httpServer.close(fn);
} else {
fn && fn();
}
};
/**
* Expose main namespace (/).
*/
var emitterMethods = Object.keys(Emitter.prototype).filter(function(key){
return typeof Emitter.prototype[key] === 'function';
});
emitterMethods.concat(['to', 'in', 'use', 'send', 'write', 'clients', 'compress']).forEach(function(fn){
Server.prototype[fn] = function(){
return this.sockets[fn].apply(this.sockets, arguments);
};
});
Namespace.flags.forEach(function(flag){
Object.defineProperty(Server.prototype, flag, {
get: function() {
this.sockets.flags = this.sockets.flags || {};
this.sockets.flags[flag] = true;
return this;
}
});
});
/**
* BC with `io.listen`
*/
Server.listen = Server;

View File

@@ -1,97 +0,0 @@
/*!
* socket.io-node
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var util = require('./util')
, toArray = util.toArray;
/**
* Log levels.
*/
var levels = [
'error'
, 'warn'
, 'info'
, 'debug'
];
/**
* Colors for log levels.
*/
var colors = [
31
, 33
, 36
, 90
];
/**
* Pads the nice output to the longest log level.
*/
function pad (str) {
var max = 0;
for (var i = 0, l = levels.length; i < l; i++)
max = Math.max(max, levels[i].length);
if (str.length < max)
return str + new Array(max - str.length + 1).join(' ');
return str;
};
/**
* Logger (console).
*
* @api public
*/
var Logger = module.exports = function (opts) {
opts = opts || {}
this.colors = false !== opts.colors;
this.level = 3;
this.enabled = true;
};
/**
* Log method.
*
* @api public
*/
Logger.prototype.log = function (type) {
var index = levels.indexOf(type);
if (index > this.level || !this.enabled)
return this;
console.log.apply(
console
, [this.colors
? ' \033[' + colors[index] + 'm' + pad(type) + ' -\033[39m'
: type + ':'
].concat(toArray(arguments).slice(1))
);
return this;
};
/**
* Generate methods.
*/
levels.forEach(function (name) {
Logger.prototype[name] = function () {
this.log.apply(this, [name].concat(toArray(arguments)));
};
});

View File

@@ -1,983 +0,0 @@
/*!
* socket.io-node
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var fs = require('fs')
, url = require('url')
, tty = require('tty')
, util = require('./util')
, store = require('./store')
, client = require('socket.io-client')
, transports = require('./transports')
, Logger = require('./logger')
, Socket = require('./socket')
, MemoryStore = require('./stores/memory')
, SocketNamespace = require('./namespace')
, Static = require('./static')
, EventEmitter = process.EventEmitter;
/**
* Export the constructor.
*/
exports = module.exports = Manager;
/**
* Default transports.
*/
var defaultTransports = exports.defaultTransports = [
'websocket'
, 'htmlfile'
, 'xhr-polling'
, 'jsonp-polling'
];
/**
* Inherited defaults.
*/
var parent = module.parent.exports
, protocol = parent.protocol;
/**
* Manager constructor.
*
* @param {HTTPServer} server
* @param {Object} options, optional
* @api public
*/
function Manager (server, options) {
this.server = server;
this.namespaces = {};
this.sockets = this.of('');
this.settings = {
origins: '*:*'
, log: true
, store: new MemoryStore
, logger: new Logger
, static: new Static(this)
, heartbeats: true
, resource: '/socket.io'
, transports: defaultTransports
, authorization: false
, blacklist: ['disconnect']
, 'log level': 3
, 'log colors': tty.isatty(process.stdout.fd)
, 'close timeout': 60
, 'heartbeat interval': 25
, 'heartbeat timeout': 60
, 'polling duration': 20
, 'flash policy server': true
, 'flash policy port': 10843
, 'destroy upgrade': true
, 'destroy buffer size': 10E7
, 'browser client': true
, 'browser client cache': true
, 'browser client minification': false
, 'browser client etag': false
, 'browser client expires': 315360000
, 'browser client gzip': false
, 'browser client handler': false
, 'client store expiration': 15
, 'match origin protocol': false
};
for (var i in options) {
this.settings[i] = options[i];
}
var self = this;
// default error handler
server.on('error', function(err) {
self.log.warn('error raised: ' + err);
});
this.initStore();
this.on('set:store', function() {
self.initStore();
});
// reset listeners
this.oldListeners = server.listeners('request');
server.removeAllListeners('request');
server.on('request', function (req, res) {
self.handleRequest(req, res);
});
server.on('upgrade', function (req, socket, head) {
self.handleUpgrade(req, socket, head);
});
server.on('close', function () {
clearInterval(self.gc);
});
server.once('listening', function () {
self.gc = setInterval(self.garbageCollection.bind(self), 10000);
});
for (var i in transports) {
if (transports[i].init) {
transports[i].init(this);
}
}
// forward-compatibility with 1.0
var self = this;
this.sockets.on('connection', function (conn) {
self.emit('connection', conn);
});
this.log.info('socket.io started');
};
Manager.prototype.__proto__ = EventEmitter.prototype
/**
* Store accessor shortcut.
*
* @api public
*/
Manager.prototype.__defineGetter__('store', function () {
var store = this.get('store');
store.manager = this;
return store;
});
/**
* Logger accessor.
*
* @api public
*/
Manager.prototype.__defineGetter__('log', function () {
var logger = this.get('logger');
logger.level = this.get('log level') || -1;
logger.colors = this.get('log colors');
logger.enabled = this.enabled('log');
return logger;
});
/**
* Static accessor.
*
* @api public
*/
Manager.prototype.__defineGetter__('static', function () {
return this.get('static');
});
/**
* Get settings.
*
* @api public
*/
Manager.prototype.get = function (key) {
return this.settings[key];
};
/**
* Set settings
*
* @api public
*/
Manager.prototype.set = function (key, value) {
if (arguments.length == 1) return this.get(key);
this.settings[key] = value;
this.emit('set:' + key, this.settings[key], key);
return this;
};
/**
* Enable a setting
*
* @api public
*/
Manager.prototype.enable = function (key) {
this.settings[key] = true;
this.emit('set:' + key, this.settings[key], key);
return this;
};
/**
* Disable a setting
*
* @api public
*/
Manager.prototype.disable = function (key) {
this.settings[key] = false;
this.emit('set:' + key, this.settings[key], key);
return this;
};
/**
* Checks if a setting is enabled
*
* @api public
*/
Manager.prototype.enabled = function (key) {
return !!this.settings[key];
};
/**
* Checks if a setting is disabled
*
* @api public
*/
Manager.prototype.disabled = function (key) {
return !this.settings[key];
};
/**
* Configure callbacks.
*
* @api public
*/
Manager.prototype.configure = function (env, fn) {
if ('function' == typeof env) {
env.call(this);
} else if (env == (process.env.NODE_ENV || 'development')) {
fn.call(this);
}
return this;
};
/**
* Initializes everything related to the message dispatcher.
*
* @api private
*/
Manager.prototype.initStore = function () {
this.handshaken = {};
this.connected = {};
this.open = {};
this.closed = {};
this.rooms = {};
this.roomClients = {};
var self = this;
this.store.subscribe('handshake', function (id, data) {
self.onHandshake(id, data);
});
this.store.subscribe('connect', function (id) {
self.onConnect(id);
});
this.store.subscribe('open', function (id) {
self.onOpen(id);
});
this.store.subscribe('join', function (id, room) {
self.onJoin(id, room);
});
this.store.subscribe('leave', function (id, room) {
self.onLeave(id, room);
});
this.store.subscribe('close', function (id) {
self.onClose(id);
});
this.store.subscribe('dispatch', function (room, packet, volatile, exceptions) {
self.onDispatch(room, packet, volatile, exceptions);
});
this.store.subscribe('disconnect', function (id) {
self.onDisconnect(id);
});
};
/**
* Called when a client handshakes.
*
* @param text
*/
Manager.prototype.onHandshake = function (id, data) {
this.handshaken[id] = data;
};
/**
* Called when a client connects (ie: transport first opens)
*
* @api private
*/
Manager.prototype.onConnect = function (id) {
this.connected[id] = true;
};
/**
* Called when a client opens a request in a different node.
*
* @api private
*/
Manager.prototype.onOpen = function (id) {
this.open[id] = true;
// if we were buffering messages for the client, clear them
if (this.closed[id]) {
var self = this;
this.store.unsubscribe('dispatch:' + id, function () {
delete self.closed[id];
});
}
// clear the current transport
if (this.transports[id]) {
this.transports[id].discard();
this.transports[id] = null;
}
};
/**
* Called when a message is sent to a namespace and/or room.
*
* @api private
*/
Manager.prototype.onDispatch = function (room, packet, volatile, exceptions) {
if (this.rooms[room]) {
for (var i = 0, l = this.rooms[room].length; i < l; i++) {
var id = this.rooms[room][i];
if (!~exceptions.indexOf(id)) {
if (this.transports[id] && this.transports[id].open) {
this.transports[id].onDispatch(packet, volatile);
} else if (!volatile) {
this.onClientDispatch(id, packet);
}
}
}
}
};
/**
* Called when a client joins a nsp / room.
*
* @api private
*/
Manager.prototype.onJoin = function (id, name) {
if (!this.roomClients[id]) {
this.roomClients[id] = {};
}
if (!this.rooms[name]) {
this.rooms[name] = [];
}
if (!~this.rooms[name].indexOf(id)) {
this.rooms[name].push(id);
this.roomClients[id][name] = true;
}
};
/**
* Called when a client leaves a nsp / room.
*
* @param private
*/
Manager.prototype.onLeave = function (id, room) {
if (this.rooms[room]) {
var index = this.rooms[room].indexOf(id);
if (index >= 0) {
this.rooms[room].splice(index, 1);
}
if (!this.rooms[room].length) {
delete this.rooms[room];
}
delete this.roomClients[id][room];
}
};
/**
* Called when a client closes a request in different node.
*
* @api private
*/
Manager.prototype.onClose = function (id) {
if (this.open[id]) {
delete this.open[id];
}
this.closed[id] = [];
var self = this;
this.store.subscribe('dispatch:' + id, function (packet, volatile) {
if (!volatile) {
self.onClientDispatch(id, packet);
}
});
};
/**
* Dispatches a message for a closed client.
*
* @api private
*/
Manager.prototype.onClientDispatch = function (id, packet) {
if (this.closed[id]) {
this.closed[id].push(packet);
}
};
/**
* Receives a message for a client.
*
* @api private
*/
Manager.prototype.onClientMessage = function (id, packet) {
if (this.namespaces[packet.endpoint]) {
this.namespaces[packet.endpoint].handlePacket(id, packet);
}
};
/**
* Fired when a client disconnects (not triggered).
*
* @api private
*/
Manager.prototype.onClientDisconnect = function (id, reason) {
for (var name in this.namespaces) {
this.namespaces[name].handleDisconnect(id, reason, typeof this.roomClients[id] !== 'undefined' &&
typeof this.roomClients[id][name] !== 'undefined');
}
this.onDisconnect(id);
};
/**
* Called when a client disconnects.
*
* @param text
*/
Manager.prototype.onDisconnect = function (id, local) {
delete this.handshaken[id];
if (this.open[id]) {
delete this.open[id];
}
if (this.connected[id]) {
delete this.connected[id];
}
if (this.transports[id]) {
this.transports[id].discard();
delete this.transports[id];
}
if (this.closed[id]) {
delete this.closed[id];
}
if (this.roomClients[id]) {
for (var room in this.roomClients[id]) {
this.onLeave(id, room);
}
delete this.roomClients[id]
}
this.store.destroyClient(id, this.get('client store expiration'));
this.store.unsubscribe('dispatch:' + id);
if (local) {
this.store.unsubscribe('message:' + id);
this.store.unsubscribe('disconnect:' + id);
}
};
/**
* Handles an HTTP request.
*
* @api private
*/
Manager.prototype.handleRequest = function (req, res) {
var data = this.checkRequest(req);
if (!data) {
for (var i = 0, l = this.oldListeners.length; i < l; i++) {
this.oldListeners[i].call(this.server, req, res);
}
return;
}
if (data.static || !data.transport && !data.protocol) {
if (data.static && this.enabled('browser client')) {
this.static.write(data.path, req, res);
} else {
res.writeHead(200);
res.end('Welcome to socket.io.');
this.log.info('unhandled socket.io url');
}
return;
}
if (data.protocol != protocol) {
res.writeHead(500);
res.end('Protocol version not supported.');
this.log.info('client protocol version unsupported');
} else {
if (data.id) {
this.handleHTTPRequest(data, req, res);
} else {
this.handleHandshake(data, req, res);
}
}
};
/**
* Handles an HTTP Upgrade.
*
* @api private
*/
Manager.prototype.handleUpgrade = function (req, socket, head) {
var data = this.checkRequest(req)
, self = this;
if (!data) {
if (this.enabled('destroy upgrade')) {
socket.end();
this.log.debug('destroying non-socket.io upgrade');
}
return;
}
req.head = head;
this.handleClient(data, req);
};
/**
* Handles a normal handshaken HTTP request (eg: long-polling)
*
* @api private
*/
Manager.prototype.handleHTTPRequest = function (data, req, res) {
req.res = res;
this.handleClient(data, req);
};
/**
* Intantiantes a new client.
*
* @api private
*/
Manager.prototype.handleClient = function (data, req) {
var socket = req.socket
, store = this.store
, self = this;
if (undefined != data.query.disconnect) {
if (this.transports[data.id] && this.transports[data.id].open) {
this.transports[data.id].onForcedDisconnect();
} else {
this.store.publish('disconnect-force:' + data.id);
}
return;
}
if (!~this.get('transports').indexOf(data.transport)) {
this.log.warn('unknown transport: "' + data.transport + '"');
req.connection.end();
return;
}
var transport = new transports[data.transport](this, data, req)
, handshaken = this.handshaken[data.id];
if (transport.disconnected) {
// failed during transport setup
req.connection.end();
return;
}
if (handshaken) {
if (transport.open) {
if (this.closed[data.id] && this.closed[data.id].length) {
transport.payload(this.closed[data.id]);
this.closed[data.id] = [];
}
this.onOpen(data.id);
this.store.publish('open', data.id);
this.transports[data.id] = transport;
}
if (!this.connected[data.id]) {
this.onConnect(data.id);
this.store.publish('connect', data.id);
// flag as used
delete handshaken.issued;
this.onHandshake(data.id, handshaken);
this.store.publish('handshake', data.id, handshaken);
// initialize the socket for all namespaces
for (var i in this.namespaces) {
var socket = this.namespaces[i].socket(data.id, true);
// echo back connect packet and fire connection event
if (i === '') {
this.namespaces[i].handlePacket(data.id, { type: 'connect' });
}
}
this.store.subscribe('message:' + data.id, function (packet) {
self.onClientMessage(data.id, packet);
});
this.store.subscribe('disconnect:' + data.id, function (reason) {
self.onClientDisconnect(data.id, reason);
});
}
} else {
if (transport.open) {
transport.error('client not handshaken', 'reconnect');
}
transport.discard();
}
};
/**
* Generates a session id.
*
* @api private
*/
Manager.prototype.generateId = function () {
return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString()
+ Math.abs(Math.random() * Math.random() * Date.now() | 0).toString();
};
/**
* Handles a handshake request.
*
* @api private
*/
Manager.prototype.handleHandshake = function (data, req, res) {
var self = this
, origin = req.headers.origin
, headers = {
'Content-Type': 'text/plain'
};
function writeErr (status, message) {
if (data.query.jsonp) {
res.writeHead(200, { 'Content-Type': 'application/javascript' });
res.end('io.j[' + data.query.jsonp + '](new Error("' + message + '"));');
} else {
res.writeHead(status, headers);
res.end(message);
}
};
function error (err) {
writeErr(500, 'handshake error');
self.log.warn('handshake error ' + err);
};
if (!this.verifyOrigin(req)) {
writeErr(403, 'handshake bad origin');
return;
}
var handshakeData = this.handshakeData(data);
if (origin) {
// https://developer.mozilla.org/En/HTTP_Access_Control
headers['Access-Control-Allow-Origin'] = origin;
headers['Access-Control-Allow-Credentials'] = 'true';
}
this.authorize(handshakeData, function (err, authorized, newData) {
if (err) return error(err);
if (authorized) {
var id = self.generateId()
, hs = [
id
, self.enabled('heartbeats') ? self.get('heartbeat timeout') || '' : ''
, self.get('close timeout') || ''
, self.transports(data).join(',')
].join(':');
if (data.query.jsonp) {
hs = 'io.j[' + data.query.jsonp + '](' + JSON.stringify(hs) + ');';
res.writeHead(200, { 'Content-Type': 'application/javascript' });
} else {
res.writeHead(200, headers);
}
res.end(hs);
self.onHandshake(id, newData || handshakeData);
self.store.publish('handshake', id, newData || handshakeData);
self.log.info('handshake authorized', id);
} else {
writeErr(403, 'handshake unauthorized');
self.log.info('handshake unauthorized');
}
})
};
/**
* Gets normalized handshake data
*
* @api private
*/
Manager.prototype.handshakeData = function (data) {
var connection = data.request.connection
, connectionAddress
, date = new Date;
if (connection.remoteAddress) {
connectionAddress = {
address: connection.remoteAddress
, port: connection.remotePort
};
} else if (connection.socket && connection.socket.remoteAddress) {
connectionAddress = {
address: connection.socket.remoteAddress
, port: connection.socket.remotePort
};
}
return {
headers: data.headers
, address: connectionAddress
, time: date.toString()
, query: data.query
, url: data.request.url
, xdomain: !!data.request.headers.origin
, secure: data.request.connection.secure
, issued: +date
};
};
/**
* Verifies the origin of a request.
*
* @api private
*/
Manager.prototype.verifyOrigin = function (request) {
var origin = request.headers.origin || request.headers.referer
, origins = this.get('origins');
if (origin === 'null') origin = '*';
if (origins.indexOf('*:*') !== -1) {
return true;
}
if (origin) {
try {
var parts = url.parse(origin);
parts.port = parts.port || 80;
var ok =
~origins.indexOf(parts.hostname + ':' + parts.port) ||
~origins.indexOf(parts.hostname + ':*') ||
~origins.indexOf('*:' + parts.port);
if (!ok) this.log.warn('illegal origin: ' + origin);
return ok;
} catch (ex) {
this.log.warn('error parsing origin');
}
}
else {
this.log.warn('origin missing from handshake, yet required by config');
}
return false;
};
/**
* Handles an incoming packet.
*
* @api private
*/
Manager.prototype.handlePacket = function (sessid, packet) {
this.of(packet.endpoint || '').handlePacket(sessid, packet);
};
/**
* Performs authentication.
*
* @param Object client request data
* @api private
*/
Manager.prototype.authorize = function (data, fn) {
if (this.get('authorization')) {
var self = this;
this.get('authorization').call(this, data, function (err, authorized) {
self.log.debug('client ' + authorized ? 'authorized' : 'unauthorized');
fn(err, authorized);
});
} else {
this.log.debug('client authorized');
fn(null, true);
}
return this;
};
/**
* Retrieves the transports adviced to the user.
*
* @api private
*/
Manager.prototype.transports = function (data) {
var transp = this.get('transports')
, ret = [];
for (var i = 0, l = transp.length; i < l; i++) {
var transport = transp[i];
if (transport) {
if (!transport.checkClient || transport.checkClient(data)) {
ret.push(transport);
}
}
}
return ret;
};
/**
* Checks whether a request is a socket.io one.
*
* @return {Object} a client request data object or `false`
* @api private
*/
var regexp = /^\/([^\/]+)\/?([^\/]+)?\/?([^\/]+)?\/?$/
Manager.prototype.checkRequest = function (req) {
var resource = this.get('resource');
var match;
if (typeof resource === 'string') {
match = req.url.substr(0, resource.length);
if (match !== resource) match = null;
} else {
match = resource.exec(req.url);
if (match) match = match[0];
}
if (match) {
var uri = url.parse(req.url.substr(match.length), true)
, path = uri.pathname || ''
, pieces = path.match(regexp);
// client request data
var data = {
query: uri.query || {}
, headers: req.headers
, request: req
, path: path
};
if (pieces) {
data.protocol = Number(pieces[1]);
data.transport = pieces[2];
data.id = pieces[3];
data.static = !!this.static.has(path);
};
return data;
}
return false;
};
/**
* Declares a socket namespace
*
* @api public
*/
Manager.prototype.of = function (nsp) {
if (this.namespaces[nsp]) {
return this.namespaces[nsp];
}
return this.namespaces[nsp] = new SocketNamespace(this, nsp);
};
/**
* Perform garbage collection on long living objects and properties that cannot
* be removed automatically.
*
* @api private
*/
Manager.prototype.garbageCollection = function () {
// clean up unused handshakes
var ids = Object.keys(this.handshaken)
, i = ids.length
, now = Date.now()
, handshake;
while (i--) {
handshake = this.handshaken[ids[i]];
if ('issued' in handshake && (now - handshake.issued) >= 3E4) {
this.onDisconnect(ids[i]);
}
}
};

View File

@@ -1,355 +1,272 @@
/**
* Module dependencies.
*/
var Socket = require('./socket')
, EventEmitter = process.EventEmitter
, parser = require('./parser')
, util = require('./util');
var Socket = require('./socket');
var Emitter = require('events').EventEmitter;
var parser = require('socket.io-parser');
var debug = require('debug')('socket.io:namespace');
/**
* Exports the constructor.
* Module exports.
*/
exports = module.exports = SocketNamespace;
module.exports = exports = Namespace;
/**
* Constructor.
* Blacklisted events.
*/
exports.events = [
'connect', // for symmetry with client
'connection',
'newListener'
];
/**
* Flags.
*/
exports.flags = [
'json',
'volatile',
'local'
];
/**
* `EventEmitter#emit` reference.
*/
var emit = Emitter.prototype.emit;
/**
* Namespace constructor.
*
* @api public.
* @param {Server} server instance
* @param {Socket} name
* @api private
*/
function SocketNamespace (mgr, name) {
this.manager = mgr;
this.name = name || '';
function Namespace(server, name){
this.name = name;
this.server = server;
this.sockets = {};
this.auth = false;
this.setFlags();
};
this.connected = {};
this.fns = [];
this.ids = 0;
this.rooms = [];
this.flags = {};
this.initAdapter();
}
/**
* Inherits from EventEmitter.
* Inherits from `EventEmitter`.
*/
SocketNamespace.prototype.__proto__ = EventEmitter.prototype;
Namespace.prototype.__proto__ = Emitter.prototype;
/**
* Copies emit since we override it.
*
* @api private
* Apply flags from `Socket`.
*/
SocketNamespace.prototype.$emit = EventEmitter.prototype.emit;
/**
* Retrieves all clients as Socket instances as an array.
*
* @api public
*/
SocketNamespace.prototype.clients = function (room) {
var room = this.name + (room !== undefined ?
'/' + room : '');
if (!this.manager.rooms[room]) {
return [];
}
return this.manager.rooms[room].map(function (id) {
return this.socket(id);
}, this);
};
/**
* Access logger interface.
*
* @api public
*/
SocketNamespace.prototype.__defineGetter__('log', function () {
return this.manager.log;
});
/**
* Access store.
*
* @api public
*/
SocketNamespace.prototype.__defineGetter__('store', function () {
return this.manager.store;
});
/**
* JSON message flag.
*
* @api public
*/
SocketNamespace.prototype.__defineGetter__('json', function () {
this.flags.json = true;
return this;
});
/**
* Volatile message flag.
*
* @api public
*/
SocketNamespace.prototype.__defineGetter__('volatile', function () {
this.flags.volatile = true;
return this;
});
/**
* Overrides the room to relay messages to (flag).
*
* @api public
*/
SocketNamespace.prototype.in = SocketNamespace.prototype.to = function (room) {
this.flags.endpoint = this.name + (room ? '/' + room : '');
return this;
};
/**
* Adds a session id we should prevent relaying messages to (flag).
*
* @api public
*/
SocketNamespace.prototype.except = function (id) {
this.flags.exceptions.push(id);
return this;
};
/**
* Sets the default flags.
*
* @api private
*/
SocketNamespace.prototype.setFlags = function () {
this.flags = {
endpoint: this.name
, exceptions: []
};
return this;
};
/**
* Sends out a packet.
*
* @api private
*/
SocketNamespace.prototype.packet = function (packet) {
packet.endpoint = this.name;
var store = this.store
, log = this.log
, volatile = this.flags.volatile
, exceptions = this.flags.exceptions
, packet = parser.encodePacket(packet);
this.manager.onDispatch(this.flags.endpoint, packet, volatile, exceptions);
this.store.publish('dispatch', this.flags.endpoint, packet, volatile, exceptions);
this.setFlags();
return this;
};
/**
* Sends to everyone.
*
* @api public
*/
SocketNamespace.prototype.send = function (data) {
return this.packet({
type: this.flags.json ? 'json' : 'message'
, data: data
exports.flags.forEach(function(flag){
Object.defineProperty(Namespace.prototype, flag, {
get: function() {
this.flags[flag] = true;
return this;
}
});
});
/**
* Initializes the `Adapter` for this nsp.
* Run upon changing adapter by `Server#adapter`
* in addition to the constructor.
*
* @api private
*/
Namespace.prototype.initAdapter = function(){
this.adapter = new (this.server.adapter())(this);
};
/**
* Emits to everyone (override).
* Sets up namespace middleware.
*
* @return {Namespace} self
* @api public
*/
SocketNamespace.prototype.emit = function (name) {
if (name == 'newListener') {
return this.$emit.apply(this, arguments);
}
return this.packet({
type: 'event'
, name: name
, args: util.toArray(arguments).slice(1)
});
};
/**
* Retrieves or creates a write-only socket for a client, unless specified.
*
* @param {Boolean} whether the socket will be readable when initialized
* @api public
*/
SocketNamespace.prototype.socket = function (sid, readable) {
if (!this.sockets[sid]) {
this.sockets[sid] = new Socket(this.manager, sid, this, readable);
}
return this.sockets[sid];
};
/**
* Sets authorization for this namespace.
*
* @api public
*/
SocketNamespace.prototype.authorization = function (fn) {
this.auth = fn;
Namespace.prototype.use = function(fn){
debug('removing initial packet');
delete this.server.eio.initialPacket;
this.fns.push(fn);
return this;
};
/**
* Called when a socket disconnects entirely.
* Executes the middleware for an incoming client.
*
* @param {Socket} socket that will get added
* @param {Function} fn last fn call in the middleware
* @api private
*/
SocketNamespace.prototype.handleDisconnect = function (sid, reason, raiseOnDisconnect) {
if (this.sockets[sid] && this.sockets[sid].readable) {
if (raiseOnDisconnect) this.sockets[sid].onDisconnect(reason);
delete this.sockets[sid];
}
};
Namespace.prototype.run = function(socket, fn){
var fns = this.fns.slice(0);
if (!fns.length) return fn(null);
/**
* Performs authentication.
*
* @param Object client request data
* @api private
*/
function run(i){
fns[i](socket, function(err){
// upon error, short-circuit
if (err) return fn(err);
SocketNamespace.prototype.authorize = function (data, fn) {
if (this.auth) {
var self = this;
// if no middleware left, summon callback
if (!fns[i + 1]) return fn(null);
this.auth.call(this, data, function (err, authorized) {
self.log.debug('client ' +
(authorized ? '' : 'un') + 'authorized for ' + self.name);
fn(err, authorized);
// go on to next
run(i + 1);
});
}
run(0);
};
/**
* Targets a room when emitting.
*
* @param {String} name
* @return {Namespace} self
* @api public
*/
Namespace.prototype.to =
Namespace.prototype.in = function(name){
if (!~this.rooms.indexOf(name)) this.rooms.push(name);
return this;
};
/**
* Adds a new client.
*
* @return {Socket}
* @api private
*/
Namespace.prototype.add = function(client, query, fn){
debug('adding socket to nsp %s', this.name);
var socket = new Socket(this, client, query);
var self = this;
this.run(socket, function(err){
process.nextTick(function(){
if ('open' == client.conn.readyState) {
if (err) return socket.error(err.data || err.message);
// track socket
self.sockets[socket.id] = socket;
// it's paramount that the internal `onconnect` logic
// fires before user-set events to prevent state order
// violations (such as a disconnection before the connection
// logic is complete)
socket.onconnect();
if (fn) fn();
// fire user-set events
self.emit('connect', socket);
self.emit('connection', socket);
} else {
debug('next called after client was closed - ignoring socket');
}
});
});
return socket;
};
/**
* Removes a client. Called by each `Socket`.
*
* @api private
*/
Namespace.prototype.remove = function(socket){
if (this.sockets.hasOwnProperty(socket.id)) {
delete this.sockets[socket.id];
} else {
this.log.debug('client authorized for ' + this.name);
fn(null, true);
debug('ignoring remove for %s', socket.id);
}
};
/**
* Emits to all clients.
*
* @return {Namespace} self
* @api public
*/
Namespace.prototype.emit = function(ev){
if (~exports.events.indexOf(ev)) {
emit.apply(this, arguments);
} else {
// set up packet object
var args = Array.prototype.slice.call(arguments);
var packet = { type: parser.EVENT, data: args };
if ('function' == typeof args[args.length - 1]) {
throw new Error('Callbacks are not supported when broadcasting');
}
this.adapter.broadcast(packet, {
rooms: this.rooms,
flags: this.flags
});
this.rooms = [];
this.flags = {};
}
return this;
};
/**
* Handles a packet.
* Sends a `message` event to all clients.
*
* @api private
* @return {Namespace} self
* @api public
*/
SocketNamespace.prototype.handlePacket = function (sessid, packet) {
var socket = this.socket(sessid)
, dataAck = packet.ack == 'data'
, manager = this.manager
, self = this;
function ack () {
self.log.debug('sending data ack packet');
socket.packet({
type: 'ack'
, args: util.toArray(arguments)
, ackId: packet.id
});
};
function error (err) {
self.log.warn('handshake error ' + err + ' for ' + self.name);
socket.packet({ type: 'error', reason: err });
};
function connect () {
self.manager.onJoin(sessid, self.name);
self.store.publish('join', sessid, self.name);
// packet echo
socket.packet({ type: 'connect' });
// emit connection event
self.$emit('connection', socket);
};
switch (packet.type) {
case 'connect':
if (packet.endpoint == '') {
connect();
} else {
var handshakeData = manager.handshaken[sessid];
this.authorize(handshakeData, function (err, authorized, newData) {
if (err) return error(err);
if (authorized) {
manager.onHandshake(sessid, newData || handshakeData);
self.store.publish('handshake', sessid, newData || handshakeData);
connect();
} else {
error('unauthorized');
}
});
}
break;
case 'ack':
if (socket.acks[packet.ackId]) {
socket.acks[packet.ackId].apply(socket, packet.args);
} else {
this.log.info('unknown ack packet');
}
break;
case 'event':
// check if the emitted event is not blacklisted
if (-~manager.get('blacklist').indexOf(packet.name)) {
this.log.debug('ignoring blacklisted event `' + packet.name + '`');
} else {
var params = [packet.name].concat(packet.args);
if (dataAck) {
params.push(ack);
}
socket.$emit.apply(socket, params);
}
break;
case 'disconnect':
this.manager.onLeave(sessid, this.name);
this.store.publish('leave', sessid, this.name);
socket.$emit('disconnect', packet.reason || 'packet');
break;
case 'json':
case 'message':
var params = ['message', packet.data];
if (dataAck)
params.push(ack);
socket.$emit.apply(socket, params);
};
Namespace.prototype.send =
Namespace.prototype.write = function(){
var args = Array.prototype.slice.call(arguments);
args.unshift('message');
this.emit.apply(this, args);
return this;
};
/**
* Gets a list of clients.
*
* @return {Namespace} self
* @api public
*/
Namespace.prototype.clients = function(fn){
this.adapter.clients(this.rooms, fn);
// reset rooms for scenario:
// .in('room').clients() (GH-1978)
this.rooms = [];
return this;
};
/**
* Sets the compress flag.
*
* @param {Boolean} compress if `true`, compresses the sending data
* @return {Socket} self
* @api public
*/
Namespace.prototype.compress = function(compress){
this.flags.compress = compress;
return this;
};

View File

@@ -1,249 +0,0 @@
/*!
* socket.io-node
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
/**
* Packet types.
*/
var packets = exports.packets = {
'disconnect': 0
, 'connect': 1
, 'heartbeat': 2
, 'message': 3
, 'json': 4
, 'event': 5
, 'ack': 6
, 'error': 7
, 'noop': 8
}
, packetslist = Object.keys(packets);
/**
* Errors reasons.
*/
var reasons = exports.reasons = {
'transport not supported': 0
, 'client not handshaken': 1
, 'unauthorized': 2
}
, reasonslist = Object.keys(reasons);
/**
* Errors advice.
*/
var advice = exports.advice = {
'reconnect': 0
}
, advicelist = Object.keys(advice);
/**
* Encodes a packet.
*
* @api private
*/
exports.encodePacket = function (packet) {
var type = packets[packet.type]
, id = packet.id || ''
, endpoint = packet.endpoint || ''
, ack = packet.ack
, data = null;
switch (packet.type) {
case 'message':
if (packet.data !== '')
data = packet.data;
break;
case 'event':
var ev = { name: packet.name };
if (packet.args && packet.args.length) {
ev.args = packet.args;
}
data = JSON.stringify(ev);
break;
case 'json':
data = JSON.stringify(packet.data);
break;
case 'ack':
data = packet.ackId
+ (packet.args && packet.args.length
? '+' + JSON.stringify(packet.args) : '');
break;
case 'connect':
if (packet.qs)
data = packet.qs;
break;
case 'error':
var reason = packet.reason ? reasons[packet.reason] : ''
, adv = packet.advice ? advice[packet.advice] : ''
if (reason !== '' || adv !== '')
data = reason + (adv !== '' ? ('+' + adv) : '')
break;
}
// construct packet with required fragments
var encoded = type + ':' + id + (ack == 'data' ? '+' : '') + ':' + endpoint;
// data fragment is optional
if (data !== null && data !== undefined)
encoded += ':' + data;
return encoded;
};
/**
* Encodes multiple messages (payload).
*
* @param {Array} messages
* @api private
*/
exports.encodePayload = function (packets) {
var decoded = '';
if (packets.length == 1)
return packets[0];
for (var i = 0, l = packets.length; i < l; i++) {
var packet = packets[i];
decoded += '\ufffd' + packet.length + '\ufffd' + packets[i]
}
return decoded;
};
/**
* Decodes a packet
*
* @api private
*/
var regexp = /([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;
/**
* Wrap the JSON.parse in a seperate function the crankshaft optimizer will
* only punish this function for the usage for try catch
*
* @api private
*/
function parse (data) {
try { return JSON.parse(data) }
catch (e) { return false }
}
exports.decodePacket = function (data) {
var pieces = data.match(regexp);
if (!pieces) return {};
var id = pieces[2] || ''
, data = pieces[5] || ''
, packet = {
type: packetslist[pieces[1]]
, endpoint: pieces[4] || ''
};
// whether we need to acknowledge the packet
if (id) {
packet.id = id;
if (pieces[3])
packet.ack = 'data';
else
packet.ack = true;
}
// handle different packet types
switch (packet.type) {
case 'message':
packet.data = data || '';
break;
case 'event':
pieces = parse(data);
if (pieces) {
packet.name = pieces.name;
packet.args = pieces.args;
}
packet.args = packet.args || [];
break;
case 'json':
packet.data = parse(data);
break;
case 'connect':
packet.qs = data || '';
break;
case 'ack':
pieces = data.match(/^([0-9]+)(\+)?(.*)/);
if (pieces) {
packet.ackId = pieces[1];
packet.args = [];
if (pieces[3]) {
packet.args = parse(pieces[3]) || [];
}
}
break;
case 'error':
pieces = data.split('+');
packet.reason = reasonslist[pieces[0]] || '';
packet.advice = advicelist[pieces[1]] || '';
}
return packet;
};
/**
* Decodes data payload. Detects multiple messages
*
* @return {Array} messages
* @api public
*/
exports.decodePayload = function (data) {
if (undefined == data || null == data) {
return [];
}
if (data[0] == '\ufffd') {
var ret = [];
for (var i = 1, length = ''; i < data.length; i++) {
if (data[i] == '\ufffd') {
ret.push(exports.decodePacket(data.substr(i + 1, length)));
i += Number(length) + 1;
length = '';
} else {
length += data[i];
}
}
return ret;
} else {
return [exports.decodePacket(data)];
}
};

View File

@@ -1,136 +0,0 @@
/*!
* socket.io-node
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var client = require('socket.io-client');
/**
* Version.
*/
exports.version = '0.9.5';
/**
* Supported protocol version.
*/
exports.protocol = 1;
/**
* Client that we serve.
*/
exports.clientVersion = client.version;
/**
* Attaches a manager
*
* @param {HTTPServer/Number} a HTTP/S server or a port number to listen on.
* @param {Object} opts to be passed to Manager and/or http server
* @param {Function} callback if a port is supplied
* @api public
*/
exports.listen = function (server, options, fn) {
if ('function' == typeof options) {
fn = options;
options = {};
}
if ('undefined' == typeof server) {
// create a server that listens on port 80
server = 80;
}
if ('number' == typeof server) {
// if a port number is passed
var port = server;
if (options && options.key)
server = require('https').createServer(options);
else
server = require('http').createServer();
// default response
server.on('request', function (req, res) {
res.writeHead(200);
res.end('Welcome to socket.io.');
});
server.listen(port, fn);
}
// otherwise assume a http/s server
return new exports.Manager(server, options);
};
/**
* Manager constructor.
*
* @api public
*/
exports.Manager = require('./manager');
/**
* Transport constructor.
*
* @api public
*/
exports.Transport = require('./transport');
/**
* Socket constructor.
*
* @api public
*/
exports.Socket = require('./socket');
/**
* Static constructor.
*
* @api public
*/
exports.Static = require('./static');
/**
* Store constructor.
*
* @api public
*/
exports.Store = require('./store');
/**
* Memory Store constructor.
*
* @api public
*/
exports.MemoryStore = require('./stores/memory');
/**
* Redis Store constructor.
*
* @api public
*/
exports.RedisStore = require('./stores/redis');
/**
* Parser.
*
* @api public
*/
exports.parser = require('./parser');

View File

@@ -1,369 +1,554 @@
/*!
* socket.io-node
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var parser = require('./parser')
, util = require('./util')
, EventEmitter = process.EventEmitter
var Emitter = require('events').EventEmitter;
var parser = require('socket.io-parser');
var url = require('url');
var debug = require('debug')('socket.io:socket');
var assign = require('object-assign');
/**
* Export the constructor.
* Module exports.
*/
exports = module.exports = Socket;
module.exports = exports = Socket;
/**
* Default error event listener to prevent uncaught exceptions.
*/
var defaultError = function () {};
/**
* Socket constructor.
* Blacklisted events.
*
* @param {Manager} manager instance
* @param {String} session id
* @param {Namespace} namespace the socket belongs to
* @param {Boolean} whether the
* @api public
*/
function Socket (manager, id, nsp, readable) {
this.id = id;
this.namespace = nsp;
this.manager = manager;
this.disconnected = false;
this.ackPackets = 0;
exports.events = [
'error',
'connect',
'disconnect',
'disconnecting',
'newListener',
'removeListener'
];
/**
* Flags.
*
* @api private
*/
var flags = [
'json',
'volatile',
'broadcast'
];
/**
* `EventEmitter#emit` reference.
*/
var emit = Emitter.prototype.emit;
/**
* Interface to a `Client` for a given `Namespace`.
*
* @param {Namespace} nsp
* @param {Client} client
* @api public
*/
function Socket(nsp, client, query){
this.nsp = nsp;
this.server = nsp.server;
this.adapter = this.nsp.adapter;
this.id = nsp.name !== '/' ? nsp.name + '#' + client.id : client.id;
this.client = client;
this.conn = client.conn;
this.rooms = {};
this.acks = {};
this.setFlags();
this.readable = readable;
this.store = this.manager.store.client(this.id);
this.on('error', defaultError);
};
this.connected = true;
this.disconnected = false;
this.handshake = this.buildHandshake(query);
this.fns = [];
this.flags = {};
this._rooms = [];
}
/**
* Inherits from EventEmitter.
* Inherits from `EventEmitter`.
*/
Socket.prototype.__proto__ = EventEmitter.prototype;
Socket.prototype.__proto__ = Emitter.prototype;
/**
* Accessor shortcut for the handshake data
*
* @api private
* Apply flags from `Socket`.
*/
Socket.prototype.__defineGetter__('handshake', function () {
return this.manager.handshaken[this.id];
});
/**
* Accessor shortcut for the transport type
*
* @api private
*/
Socket.prototype.__defineGetter__('transport', function () {
return this.manager.transports[this.id].name;
});
/**
* Accessor shortcut for the logger.
*
* @api private
*/
Socket.prototype.__defineGetter__('log', function () {
return this.manager.log;
});
/**
* JSON message flag.
*
* @api public
*/
Socket.prototype.__defineGetter__('json', function () {
this.flags.json = true;
return this;
});
/**
* Volatile message flag.
*
* @api public
*/
Socket.prototype.__defineGetter__('volatile', function () {
this.flags.volatile = true;
return this;
});
/**
* Broadcast message flag.
*
* @api public
*/
Socket.prototype.__defineGetter__('broadcast', function () {
this.flags.broadcast = true;
return this;
});
/**
* Overrides the room to broadcast messages to (flag)
*
* @api public
*/
Socket.prototype.to = Socket.prototype.in = function (room) {
this.flags.room = room;
return this;
};
/**
* Resets flags
*
* @api private
*/
Socket.prototype.setFlags = function () {
this.flags = {
endpoint: this.namespace.name
, room: ''
};
return this;
};
/**
* Triggered on disconnect
*
* @api private
*/
Socket.prototype.onDisconnect = function (reason) {
if (!this.disconnected) {
this.$emit('disconnect', reason);
this.disconnected = true;
}
};
/**
* Joins a user to a room.
*
* @api public
*/
Socket.prototype.join = function (name, fn) {
var nsp = this.namespace.name
, name = (nsp + '/') + name;
this.manager.onJoin(this.id, name);
this.manager.store.publish('join', this.id, name);
if (fn) {
this.log.warn('Client#join callback is deprecated');
fn();
}
return this;
};
/**
* Un-joins a user from a room.
*
* @api public
*/
Socket.prototype.leave = function (name, fn) {
var nsp = this.namespace.name
, name = (nsp + '/') + name;
this.manager.onLeave(this.id, name);
this.manager.store.publish('leave', this.id, name);
if (fn) {
this.log.warn('Client#leave callback is deprecated');
fn();
}
return this;
};
/**
* Transmits a packet.
*
* @api private
*/
Socket.prototype.packet = function (packet) {
if (this.flags.broadcast) {
this.log.debug('broadcasting packet');
this.namespace.in(this.flags.room).except(this.id).packet(packet);
} else {
packet.endpoint = this.flags.endpoint;
packet = parser.encodePacket(packet);
this.dispatch(packet, this.flags.volatile);
}
this.setFlags();
return this;
};
/**
* Dispatches a packet
*
* @api private
*/
Socket.prototype.dispatch = function (packet, volatile) {
if (this.manager.transports[this.id] && this.manager.transports[this.id].open) {
this.manager.transports[this.id].onDispatch(packet, volatile);
} else {
if (!volatile) {
this.manager.onClientDispatch(this.id, packet, volatile);
flags.forEach(function(flag){
Object.defineProperty(Socket.prototype, flag, {
get: function() {
this.flags[flag] = true;
return this;
}
});
});
this.manager.store.publish('dispatch:' + this.id, packet, volatile);
/**
* `request` engine.io shortcut.
*
* @api public
*/
Object.defineProperty(Socket.prototype, 'request', {
get: function() {
return this.conn.request;
}
});
/**
* Builds the `handshake` BC object
*
* @api private
*/
Socket.prototype.buildHandshake = function(query){
var self = this;
function buildQuery(){
var requestQuery = url.parse(self.request.url, true).query;
//if socket-specific query exist, replace query strings in requestQuery
return assign({}, query, requestQuery);
}
return {
headers: this.request.headers,
time: (new Date) + '',
address: this.conn.remoteAddress,
xdomain: !!this.request.headers.origin,
secure: !!this.request.connection.encrypted,
issued: +(new Date),
url: this.request.url,
query: buildQuery()
};
};
/**
* Stores data for the client.
* Emits to this client.
*
* @return {Socket} self
* @api public
*/
Socket.prototype.set = function (key, value, fn) {
this.store.set(key, value, fn);
return this;
};
Socket.prototype.emit = function(ev){
if (~exports.events.indexOf(ev)) {
emit.apply(this, arguments);
} else {
var args = Array.prototype.slice.call(arguments);
var packet = {
type: parser.EVENT,
data: args
};
/**
* Retrieves data for the client
*
* @api public
*/
Socket.prototype.get = function (key, fn) {
this.store.get(key, fn);
return this;
};
/**
* Checks data for the client
*
* @api public
*/
Socket.prototype.has = function (key, fn) {
this.store.has(key, fn);
return this;
};
/**
* Deletes data for the client
*
* @api public
*/
Socket.prototype.del = function (key, fn) {
this.store.del(key, fn);
return this;
};
/**
* Kicks client
*
* @api public
*/
Socket.prototype.disconnect = function () {
if (!this.disconnected) {
this.log.info('booting client');
if ('' === this.namespace.name) {
if (this.manager.transports[this.id] && this.manager.transports[this.id].open) {
this.manager.transports[this.id].onForcedDisconnect();
} else {
this.manager.onClientDisconnect(this.id);
this.manager.store.publish('disconnect:' + this.id);
// access last argument to see if it's an ACK callback
if (typeof args[args.length - 1] === 'function') {
if (this._rooms.length || this.flags.broadcast) {
throw new Error('Callbacks are not supported when broadcasting');
}
} else {
this.packet({type: 'disconnect'});
this.manager.onLeave(this.id, this.namespace.name);
this.$emit('disconnect', 'booted');
debug('emitting packet with ack id %d', this.nsp.ids);
this.acks[this.nsp.ids] = args.pop();
packet.id = this.nsp.ids++;
}
}
if (this._rooms.length || this.flags.broadcast) {
this.adapter.broadcast(packet, {
except: [this.id],
rooms: this._rooms,
flags: this.flags
});
} else {
// dispatch packet
this.packet(packet, this.flags);
}
// reset flags
this._rooms = [];
this.flags = {};
}
return this;
};
/**
* Send a message.
* Targets a room when broadcasting.
*
* @param {String} name
* @return {Socket} self
* @api public
*/
Socket.prototype.send = function (data, fn) {
var packet = {
type: this.flags.json ? 'json' : 'message'
, data: data
};
if (fn) {
packet.id = ++this.ackPackets;
packet.ack = true;
this.acks[packet.id] = fn;
}
return this.packet(packet);
Socket.prototype.to =
Socket.prototype.in = function(name){
if (!~this._rooms.indexOf(name)) this._rooms.push(name);
return this;
};
/**
* Original emit function.
* Sends a `message` event.
*
* @return {Socket} self
* @api public
*/
Socket.prototype.send =
Socket.prototype.write = function(){
var args = Array.prototype.slice.call(arguments);
args.unshift('message');
this.emit.apply(this, args);
return this;
};
/**
* Writes a packet.
*
* @param {Object} packet object
* @param {Object} opts options
* @api private
*/
Socket.prototype.packet = function(packet, opts){
packet.nsp = this.nsp.name;
opts = opts || {};
opts.compress = false !== opts.compress;
this.client.packet(packet, opts);
};
/**
* Joins a room.
*
* @param {String|Array} room or array of rooms
* @param {Function} fn optional, callback
* @return {Socket} self
* @api private
*/
Socket.prototype.join = function(rooms, fn){
debug('joining room %s', rooms);
var self = this;
if (!Array.isArray(rooms)) {
rooms = [rooms];
}
rooms = rooms.filter(function (room) {
return !self.rooms.hasOwnProperty(room);
});
if (!rooms.length) {
fn && fn(null);
return this;
}
this.adapter.addAll(this.id, rooms, function(err){
if (err) return fn && fn(err);
debug('joined room %s', rooms);
rooms.forEach(function (room) {
self.rooms[room] = room;
});
fn && fn(null);
});
return this;
};
/**
* Leaves a room.
*
* @param {String} room
* @param {Function} fn optional, callback
* @return {Socket} self
* @api private
*/
Socket.prototype.leave = function(room, fn){
debug('leave room %s', room);
var self = this;
this.adapter.del(this.id, room, function(err){
if (err) return fn && fn(err);
debug('left room %s', room);
delete self.rooms[room];
fn && fn(null);
});
return this;
};
/**
* Leave all rooms.
*
* @api private
*/
Socket.prototype.$emit = EventEmitter.prototype.emit;
Socket.prototype.leaveAll = function(){
this.adapter.delAll(this.id);
this.rooms = {};
};
/**
* Emit override for custom events.
* Called by `Namespace` upon successful
* middleware execution (ie: authorization).
* Socket is added to namespace array before
* call to join, so adapters can access it.
*
* @api private
*/
Socket.prototype.onconnect = function(){
debug('socket connected - writing packet');
this.nsp.connected[this.id] = this;
this.join(this.id);
var skip = this.nsp.name === '/' && this.nsp.fns.length === 0;
if (skip) {
debug('packet already sent in initial handshake');
} else {
this.packet({ type: parser.CONNECT });
}
};
/**
* Called with each packet. Called by `Client`.
*
* @param {Object} packet
* @api private
*/
Socket.prototype.onpacket = function(packet){
debug('got packet %j', packet);
switch (packet.type) {
case parser.EVENT:
this.onevent(packet);
break;
case parser.BINARY_EVENT:
this.onevent(packet);
break;
case parser.ACK:
this.onack(packet);
break;
case parser.BINARY_ACK:
this.onack(packet);
break;
case parser.DISCONNECT:
this.ondisconnect();
break;
case parser.ERROR:
this.emit('error', packet.data);
}
};
/**
* Called upon event packet.
*
* @param {Object} packet object
* @api private
*/
Socket.prototype.onevent = function(packet){
var args = packet.data || [];
debug('emitting event %j', args);
if (null != packet.id) {
debug('attaching ack callback to event');
args.push(this.ack(packet.id));
}
this.dispatch(args);
};
/**
* Produces an ack callback to emit with an event.
*
* @param {Number} id packet id
* @api private
*/
Socket.prototype.ack = function(id){
var self = this;
var sent = false;
return function(){
// prevent double callbacks
if (sent) return;
var args = Array.prototype.slice.call(arguments);
debug('sending ack %j', args);
self.packet({
id: id,
type: parser.ACK,
data: args
});
sent = true;
};
};
/**
* Called upon ack packet.
*
* @api private
*/
Socket.prototype.onack = function(packet){
var ack = this.acks[packet.id];
if ('function' == typeof ack) {
debug('calling ack %s with %j', packet.id, packet.data);
ack.apply(this, packet.data);
delete this.acks[packet.id];
} else {
debug('bad ack %s', packet.id);
}
};
/**
* Called upon client disconnect packet.
*
* @api private
*/
Socket.prototype.ondisconnect = function(){
debug('got disconnect packet');
this.onclose('client namespace disconnect');
};
/**
* Handles a client error.
*
* @api private
*/
Socket.prototype.onerror = function(err){
if (this.listeners('error').length) {
this.emit('error', err);
} else {
console.error('Missing error handler on `socket`.');
console.error(err.stack);
}
};
/**
* Called upon closing. Called by `Client`.
*
* @param {String} reason
* @throw {Error} optional error object
* @api private
*/
Socket.prototype.onclose = function(reason){
if (!this.connected) return this;
debug('closing socket - reason %s', reason);
this.emit('disconnecting', reason);
this.leaveAll();
this.nsp.remove(this);
this.client.remove(this);
this.connected = false;
this.disconnected = true;
delete this.nsp.connected[this.id];
this.emit('disconnect', reason);
};
/**
* Produces an `error` packet.
*
* @param {Object} err error object
* @api private
*/
Socket.prototype.error = function(err){
this.packet({ type: parser.ERROR, data: err });
};
/**
* Disconnects this client.
*
* @param {Boolean} close if `true`, closes the underlying connection
* @return {Socket} self
* @api public
*/
Socket.prototype.emit = function (ev) {
if (ev == 'newListener') {
return this.$emit.apply(this, arguments);
Socket.prototype.disconnect = function(close){
if (!this.connected) return this;
if (close) {
this.client.disconnect();
} else {
this.packet({ type: parser.DISCONNECT });
this.onclose('server namespace disconnect');
}
var args = util.toArray(arguments).slice(1)
, lastArg = args[args.length - 1]
, packet = {
type: 'event'
, name: ev
};
if ('function' == typeof lastArg) {
packet.id = ++this.ackPackets;
packet.ack = lastArg.length ? 'data' : true;
this.acks[packet.id] = lastArg;
args = args.slice(0, args.length - 1);
}
packet.args = args;
return this.packet(packet);
return this;
};
/**
* Sets the compress flag.
*
* @param {Boolean} compress if `true`, compresses the sending data
* @return {Socket} self
* @api public
*/
Socket.prototype.compress = function(compress){
this.flags.compress = compress;
return this;
};
/**
* Dispatch incoming event to socket listeners.
*
* @param {Array} event that will get emitted
* @api private
*/
Socket.prototype.dispatch = function(event){
debug('dispatching an event %j', event);
var self = this;
function dispatchSocket(err) {
process.nextTick(function(){
if (err) {
return self.error(err.data || err.message);
}
emit.apply(self, event);
});
}
this.run(event, dispatchSocket);
};
/**
* Sets up socket middleware.
*
* @param {Function} middleware function (event, next)
* @return {Socket} self
* @api public
*/
Socket.prototype.use = function(fn){
this.fns.push(fn);
return this;
};
/**
* Executes the middleware for an incoming event.
*
* @param {Array} event that will get emitted
* @param {Function} last fn call in the middleware
* @api private
*/
Socket.prototype.run = function(event, fn){
var fns = this.fns.slice(0);
if (!fns.length) return fn(null);
function run(i){
fns[i](event, function(err){
// upon error, short-circuit
if (err) return fn(err);
// if no middleware left, summon callback
if (!fns[i + 1]) return fn(null);
// go on to next
run(i + 1);
});
}
run(0);
};

View File

@@ -1,395 +0,0 @@
/*!
* socket.io-node
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var client = require('socket.io-client')
, cp = require('child_process')
, fs = require('fs')
, util = require('./util');
/**
* File type details.
*
* @api private
*/
var mime = {
js: {
type: 'application/javascript'
, encoding: 'utf8'
, gzip: true
}
, swf: {
type: 'application/x-shockwave-flash'
, encoding: 'binary'
, gzip: false
}
};
/**
* Regexp for matching custom transport patterns. Users can configure their own
* socket.io bundle based on the url structure. Different transport names are
* concatinated using the `+` char. /socket.io/socket.io+websocket.js should
* create a bundle that only contains support for the websocket.
*
* @api private
*/
var bundle = /\+((?:\+)?[\w\-]+)*(?:\.v\d+\.\d+\.\d+)?(?:\.js)$/
, versioning = /\.v\d+\.\d+\.\d+(?:\.js)$/;
/**
* Export the constructor
*/
exports = module.exports = Static;
/**
* Static constructor
*
* @api public
*/
function Static (manager) {
this.manager = manager;
this.cache = {};
this.paths = {};
this.init();
}
/**
* Initialize the Static by adding default file paths.
*
* @api public
*/
Static.prototype.init = function () {
/**
* Generates a unique id based the supplied transports array
*
* @param {Array} transports The array with transport types
* @api private
*/
function id (transports) {
var id = transports.join('').split('').map(function (char) {
return ('' + char.charCodeAt(0)).split('').pop();
}).reduce(function (char, id) {
return char +id;
});
return client.version + ':' + id;
}
/**
* Generates a socket.io-client file based on the supplied transports.
*
* @param {Array} transports The array with transport types
* @param {Function} callback Callback for the static.write
* @api private
*/
function build (transports, callback) {
client.builder(transports, {
minify: self.manager.enabled('browser client minification')
}, function (err, content) {
callback(err, content ? new Buffer(content) : null, id(transports));
}
);
}
var self = this;
// add our default static files
this.add('/static/flashsocket/WebSocketMain.swf', {
file: client.dist + '/WebSocketMain.swf'
});
this.add('/static/flashsocket/WebSocketMainInsecure.swf', {
file: client.dist + '/WebSocketMainInsecure.swf'
});
// generates dedicated build based on the available transports
this.add('/socket.io.js', function (path, callback) {
build(self.manager.get('transports'), callback);
});
this.add('/socket.io.v', { mime: mime.js }, function (path, callback) {
build(self.manager.get('transports'), callback);
});
// allow custom builds based on url paths
this.add('/socket.io+', { mime: mime.js }, function (path, callback) {
var available = self.manager.get('transports')
, matches = path.match(bundle)
, transports = [];
if (!matches) return callback('No valid transports');
// make sure they valid transports
matches[0].split('.')[0].split('+').slice(1).forEach(function (transport) {
if (!!~available.indexOf(transport)) {
transports.push(transport);
}
});
if (!transports.length) return callback('No valid transports');
build(transports, callback);
});
// clear cache when transports change
this.manager.on('set:transports', function (key, value) {
delete self.cache['/socket.io.js'];
Object.keys(self.cache).forEach(function (key) {
if (bundle.test(key)) {
delete self.cache[key];
}
});
});
};
/**
* Gzip compress buffers.
*
* @param {Buffer} data The buffer that needs gzip compression
* @param {Function} callback
* @api public
*/
Static.prototype.gzip = function (data, callback) {
var gzip = cp.spawn('gzip', ['-9', '-c', '-f', '-n'])
, encoding = Buffer.isBuffer(data) ? 'binary' : 'utf8'
, buffer = []
, err;
gzip.stdout.on('data', function (data) {
buffer.push(data);
});
gzip.stderr.on('data', function (data) {
err = data +'';
buffer.length = 0;
});
gzip.on('exit', function () {
if (err) return callback(err);
var size = 0
, index = 0
, i = buffer.length
, content;
while (i--) {
size += buffer[i].length;
}
content = new Buffer(size);
i = buffer.length;
buffer.forEach(function (buffer) {
var length = buffer.length;
buffer.copy(content, index, 0, length);
index += length;
});
buffer.length = 0;
callback(null, content);
});
gzip.stdin.end(data, encoding);
};
/**
* Is the path a static file?
*
* @param {String} path The path that needs to be checked
* @api public
*/
Static.prototype.has = function (path) {
// fast case
if (this.paths[path]) return this.paths[path];
var keys = Object.keys(this.paths)
, i = keys.length;
while (i--) {
if (-~path.indexOf(keys[i])) return this.paths[keys[i]];
}
return false;
};
/**
* Add new paths new paths that can be served using the static provider.
*
* @param {String} path The path to respond to
* @param {Options} options Options for writing out the response
* @param {Function} [callback] Optional callback if no options.file is
* supplied this would be called instead.
* @api public
*/
Static.prototype.add = function (path, options, callback) {
var extension = /(?:\.(\w{1,4}))$/.exec(path);
if (!callback && typeof options == 'function') {
callback = options;
options = {};
}
options.mime = options.mime || (extension ? mime[extension[1]] : false);
if (callback) options.callback = callback;
if (!(options.file || options.callback) || !options.mime) return false;
this.paths[path] = options;
return true;
};
/**
* Writes a static response.
*
* @param {String} path The path for the static content
* @param {HTTPRequest} req The request object
* @param {HTTPResponse} res The response object
* @api public
*/
Static.prototype.write = function (path, req, res) {
/**
* Write a response without throwing errors because can throw error if the
* response is no longer writable etc.
*
* @api private
*/
function write (status, headers, content, encoding) {
try {
res.writeHead(status, headers || undefined);
// only write content if it's not a HEAD request and we actually have
// some content to write (304's doesn't have content).
res.end(
req.method !== 'HEAD' && content ? content : ''
, encoding || undefined
);
} catch (e) {}
}
/**
* Answers requests depending on the request properties and the reply object.
*
* @param {Object} reply The details and content to reply the response with
* @api private
*/
function answer (reply) {
var cached = req.headers['if-none-match'] === reply.etag;
if (cached && self.manager.enabled('browser client etag')) {
return write(304);
}
var accept = req.headers['accept-encoding'] || ''
, gzip = !!~accept.toLowerCase().indexOf('gzip')
, mime = reply.mime
, versioned = reply.versioned
, headers = {
'Content-Type': mime.type
};
// check if we can add a etag
if (self.manager.enabled('browser client etag') && reply.etag && !versioned) {
headers['Etag'] = reply.etag;
}
// see if we need to set Expire headers because the path is versioned
if (versioned) {
var expires = self.manager.get('browser client expires');
headers['Cache-Control'] = 'private, x-gzip-ok="", max-age=' + expires;
headers['Date'] = new Date().toUTCString();
headers['Expires'] = new Date(Date.now() + (expires * 1000)).toUTCString();
}
if (gzip && reply.gzip) {
headers['Content-Length'] = reply.gzip.length;
headers['Content-Encoding'] = 'gzip';
headers['Vary'] = 'Accept-Encoding';
write(200, headers, reply.gzip.content, mime.encoding);
} else {
headers['Content-Length'] = reply.length;
write(200, headers, reply.content, mime.encoding);
}
self.manager.log.debug('served static content ' + path);
}
var self = this
, details;
// most common case first
if (this.manager.enabled('browser client cache') && this.cache[path]) {
return answer(this.cache[path]);
} else if (this.manager.get('browser client handler')) {
return this.manager.get('browser client handler').call(this, req, res);
} else if ((details = this.has(path))) {
/**
* A small helper function that will let us deal with fs and dynamic files
*
* @param {Object} err Optional error
* @param {Buffer} content The data
* @api private
*/
function ready (err, content, etag) {
if (err) {
self.manager.log.warn('Unable to serve file. ' + (err.message || err));
return write(500, null, 'Error serving static ' + path);
}
// store the result in the cache
var reply = self.cache[path] = {
content: content
, length: content.length
, mime: details.mime
, etag: etag || client.version
, versioned: versioning.test(path)
};
// check if gzip is enabled
if (details.mime.gzip && self.manager.enabled('browser client gzip')) {
self.gzip(content, function (err, content) {
if (!err) {
reply.gzip = {
content: content
, length: content.length
}
}
answer(reply);
});
} else {
answer(reply);
}
}
if (details.file) {
fs.readFile(details.file, ready);
} else if(details.callback) {
details.callback.call(this, path, ready);
} else {
write(404, null, 'File handle not found');
}
} else {
write(404, null, 'File not found');
}
};

View File

@@ -1,98 +0,0 @@
/*!
* socket.io-node
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
/**
* Expose the constructor.
*/
exports = module.exports = Store;
/**
* Module dependencies.
*/
var EventEmitter = process.EventEmitter;
/**
* Store interface
*
* @api public
*/
function Store (options) {
this.options = options;
this.clients = {};
};
/**
* Inherit from EventEmitter.
*/
Store.prototype.__proto__ = EventEmitter.prototype;
/**
* Initializes a client store
*
* @param {String} id
* @api public
*/
Store.prototype.client = function (id) {
if (!this.clients[id]) {
this.clients[id] = new (this.constructor.Client)(this, id);
}
return this.clients[id];
};
/**
* Destroys a client
*
* @api {String} sid
* @param {Number} number of seconds to expire client data
* @api private
*/
Store.prototype.destroyClient = function (id, expiration) {
if (this.clients[id]) {
this.clients[id].destroy(expiration);
delete this.clients[id];
}
return this;
};
/**
* Destroys the store
*
* @param {Number} number of seconds to expire client data
* @api private
*/
Store.prototype.destroy = function (clientExpiration) {
var keys = Object.keys(this.clients)
, count = keys.length;
for (var i = 0, l = count; i < l; i++) {
this.destroyClient(keys[i], clientExpiration);
}
this.clients = {};
return this;
};
/**
* Client.
*
* @api public
*/
Store.Client = function (store, id) {
this.store = store;
this.id = id;
};

Some files were not shown because too many files have changed in this diff Show More