-
Notifications
You must be signed in to change notification settings - Fork 4
/
chat.js
42 lines (36 loc) · 1.13 KB
/
chat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env node
// Devel mode
require.paths.unshift('../lib');
var http = require('http'),
ws = require('http/websocket'),
sys = require('sys'),
notFound = require('./shared').notFound,
sendFile = require('./shared').sendFile;
const publicDir = './public';
var chat = new ws.Server();
chat.addListener("connect", function(conn) {
sys.debug("onconnect");
this.broadcast("new connection: " + conn.remoteAddress);
});
chat.addListener("disconnect", function(conn) {
sys.debug("ondisconnect");
this.broadcast("disconnection of " + conn.remoteAddress);
})
chat.addListener("message", function(msg, conn) {
sys.debug("onmessage");
this.broadcast("Got " + msg);
});
function handler(req, res) {
sys.debug(req.method + ' ' + req.uri.path);
if (ws.askUpgrade(req)) {
sys.debug("Upgrading to WebSocket");
chat.connect(req, res);
} else {
var filePath = publicDir + req.uri.path;
sendFile(req, res, filePath);
}
}
var srv = http.createServer();
srv.addListener("request", handler);
srv.listen(8000);
sys.puts("Connected on port :8000");