-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
52 lines (42 loc) · 1.38 KB
/
Copy pathserver.js
File metadata and controls
52 lines (42 loc) · 1.38 KB
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
43
44
45
46
47
48
49
50
51
52
// HTTP Portion
var http = require('http');
var fs = require('fs'); // Using the filesystem module
var httpServer = http.createServer(requestHandler);
httpServer.listen(8080);
function requestHandler(req, res) {
// Read index.html
fs.readFile(__dirname + '/index.html',
// Callback function for reading
function (err, data) {
// if there is an error
if (err) {
res.writeHead(500);
return res.end('Error loading canvas_socket.html');
}
// Otherwise, send the data, the contents of the file
res.writeHead(200);
res.end(data);
}
);
}
// WebSocket Portion
// WebSockets work with the HTTP server
var io = require('socket.io').listen(httpServer);
// Register a callback function to run when we have an individual connection
// This is run for each individual user that connects
io.sockets.on('connection',
// We are given a websocket object in our function
function (socket) {
console.log("We have a new client: " + socket.id);
// When this user emits, client side: socket.emit('otherevent',some data);
socket.on('chatmessage', function(data) {
// Data comes in as whatever was sent, including objects
console.log("Received: 'chatmessage' " + data);
// Send it to all of the clients
socket.broadcast.emit('chatmessage', data);
});
socket.on('disconnect', function() {
console.log("Client has disconnected " + socket.id);
});
}
);