UNPKG

2.63 kBMarkdownView Raw
1# What it does
2
3###### Ability to create room variables for people that use socket.io. It was kind of strange to see that there was no room variable solution for socket.io out of the box. ######
4
5
6# How does it look?
7
8![roomdata.gif](https://bitbucket.org/repo/EaxM4K/images/4033599328-roomdata.gif)
9
10 var roomdata = require('roomdata'),
11 io.sockets.on('connection', function (socket) {
12 // Lets join/create a room:
13 roomdata.joinRoom(socket, "testroom"); // You do not have to create a room before joining it
14
15 // You can define room variables:
16 roomdata.set(socket, "gamedata", {x:4, y:20}); // Creates a room variable
17 roomdata.set(socket, "timesdied", 5); // Can also be a number,string,boolean etc
18
19 // Then on every socket that has joined the same room you can retrieve the values:
20 console.log(roomdata.get(socket, "gamedata")); // Prints: { x: 4, y: 20 }
21 console.log(roomdata.get(socket, "gamedata").y); // Prints: 20
22
23 // Incrementing timesdied
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 variables when a room is created:
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 in
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 });
40![Example1](http://s14.postimg.org/7j43w0b81/roomdata1.png)
41
42
43# How do I use it?
44
45## 1. Start by installing the package:
46 npm install roomdata
47
48## 2. Put this in your nodejs server file:
49
50 var roomdata = require('roomdata');
51
52## 3. Now you can do stuff like:
53
54 roomdata.joinRoom(socket, "testroom");
55
56 roomdata.set(socket, "gamedata", {x:4, y:20});
57
58 console.log(roomdata.get(socket, "gamedata")); // Prints: { x: 4, y: 20 }
59 console.log(roomdata.get(socket, "gamedata").y); // Prints: 20
60
61## 4. Make sure to define a disconnect handler and call roomdata.leaveRoom with socket as parameter
62
63 socket.on('disconnect', function() {
64 roomdata.leaveRoom(socket);
65 });
66
67# Contact
68 You can contact me at specamps@gmail.com
69
70