UNPKG

1.76 kBJavaScriptView Raw
1var connect = require('connect'),
2serveStatic = require('serve-static'),
3app = connect();
4
5app.use(serveStatic('public', {'index': 'index.html'})).listen(80);
6
7var roomdata = require('./roomdata'),
8io = require('socket.io').listen(8080);
9
10io.sockets.on('connection', function (socket) {
11 // Lets join/create a room:
12 roomdata.joinRoom(socket, "testroom"); // You do not have to create a room before joining it
13
14 // You can define room variables:
15 roomdata.set(socket, "gamedata", {x:4, y:20}); // Creates a room variable
16 roomdata.set(socket, "timesdied", 5); // Can also be a number,string,boolean etc
17
18 // Then on every socket that has joined the same room you can retrieve the values:
19 console.log(roomdata.get(socket, "gamedata")); // Prints: { x: 4, y: 20 }
20 console.log(roomdata.get(socket, "gamedata").y); // Prints: 20
21
22
23 // Incrementing a number for example can also be done
24 var inc = roomdata.get(socket, "timesdied") + 10;
25 roomdata.set(socket, "timesdied", inc);
26 console.log(roomdata.get(socket, "timesdied")); // Prints: 15
27
28 // Standard created variables when a room is made:
29 console.log(roomdata.get(socket, "users")); // Prints: array full of current users in room (socket.id)
30 console.log(roomdata.get(socket, "room")); // Prints: current room name this socket is
31 console.log(roomdata.get(socket, "owner")); // Prints: the socket.id that created the room
32
33 // Important: It is not yet possible to use get and set if a socket is in two rooms at once!
34
35 // Make sure to define a on disconnect handler and call roomdata.leaveRoom with the socket as parameter or roomdata.get(socket, "users") will not function well!
36 socket.on('disconnect', function() {
37 roomdata.leaveRoom(socket);
38 });
39});
\No newline at end of file