Socket-Mansion
Socket-Mansion helps you connect your sockets to rooms, while also keeping check on where your users are.
This lets you focus on the actual function of the room instead of worrying about connections.
You should see your socket-mansion as a container for all rooms, while the modules you inject are rooms, you decide the states of the rooms.
npm install socket-mansion --save
How to use (in 4 steps)
Step 1. Create room
Constructor: Your room modules need to have, io and id as parameters.
{ thisio = io thisid = id}
User joins:
When a user joins the room, room.setup(socket, userObj)
will be called. An example
how your setup function can look like.
roomprototype { const user = name: userObjusername id: socketid socket;}
User leaves:
When a user leaves the room, room.off(socket)
will be called. This is a good
time to maybe update your rooms state, or remove events for the socket. Example:
roomprototype { socket}
Step 2. Add your room module to the mansion before server.listen()
var http = var app = const socketMansion = const chat = chatconst game = game const modules = module: chat name: "chat" module: game name: "game" var server = http
Step 3. Client side
The mansion has some events already created for you, so you can easily connect to your room-events. Before I show you, make sure you setup your user before using any emits.
Setup user:
socket // Client emitsid: socketid user: userObj // Server saves
Events:
Here are the events, as you can see on the create room
we have a third argument
which is the modules name you want to use.
socket socket socket // Triggers above socket // Triggers above socket socket socket socket // does not trigger .off, you should leave aswell
Step 4. Wait.. won't my room events be the same if I create a new room with the same module?
Yes you are correct, to fix this we can use the id
that we get in our room
constructor. Then we can do something like this
// "room chat" function on server-sidechatprototype { socket}// clientsocketsocket// hello!
Example with React
Instead of me posting lots of code, then please checkout
Test your room modules easily with mocha
A test with mocha and sockets can look like this,
;
Wouldn't it be great if you could remove the following,
// var client1 = io(socketURL, options);// client1.on('connect', () => {//// var client2 = io(socketURL, options);// client2.on('connect', () => {//// client1.emit('setup user', {name: "player1"});// client2.emit('setup user', {name: "player2"});//// client1.emit(`create room`, `room1`, module);//// client1.emit('join room', `room1`);// client2.emit('join room', `room1`); client2;// });// });
You can use the setupRoomTest()
to achieve something like this,
;