dok-socket
Uses socket.io to handle data sharing easily via sockets.
This is the client component.
-
Server package:
-
Client package:
- NPM: https://www.npmjs.com/package/dok-socket-client
- Github:
Setup server on Node.js:
const serveSocket = ; const app = ;const io server = ;const httpServer = server;
This opens the socket on the local server.
Then import the client (use browserify to get the Nodejs module working in browser).
Create main.js
const SocketClient = ; moduleexports = SocketClient;
Browserify:
browserify main.js --standalone dok-lib > json-compact.js
Use:
const SocketClient} = dokLib; const socket = backupServer;
Now you can use socket
to share data or call functions in real time.
Join / leave a room
// To join a room:socket; // To leave a room:socket;
As soon as you join a room, data gets shared across.
Sharing data
Once you joined a room, a simple way to handle real-time communication is to have all clients share a piece in a big pool of data.
// To share data with other clients in the roomsocket;
Data can be any serializable object. Then you can access all data shared within the room:
// This is the number of data availableconst count = socket; // Then iterate through all the data:for let i = 0; i < count; i++ const data = socket; // if you need, you can use the client's id: const id = socket; const dataById = socket; // ...
Note data socket.getSharedData(0)
is your own data. If you haven't set it, it will be empty ({}
);
You can just read data in a loop repeatedly, or listen to data change:
socket;
Traditionally, we have each client share a model that describe a character in a game. Each client continously update their own client, and processes data for all clients including self, to display the various characters in a game.
Call methods accross clients in real-time
Another way to handle real-time communication is to call methods across several clients. Calling a method on one client would call the exact same method on all clients automatically.
objmethod = socket;
Now, when you call obj.method
, it will execute whatever obj.method
was doing, but it will also call obj.method
on all other clients (assuming all clients also ran the same code that wraps their own obj.method
under name
).
For instance:
consolelog = socket; console; // This logs the messsage "Hello everybody!" on everyone's console, including your own.
This is an easy way to use socket.io. If you have your own use case, I would suggest you code your own implementation using socket.io. The package is available here: https://socket.io/