socket-event
WebSocket client-server communication library.
About
WebSoket technology is awesome. But it comes a little hard to start using it. Also you have some problems building big apps with websockets.
In this library we still have imitation of methods (get, post, put, delete), added new one "notify". The connection goes with websockets and we have ability to set callback on front and handler on back. Also added one method "notify". It should serve to send any kind of notifications between front and end. You can build client => server event system on top of this "notify" method.
Actually all these methods work identically. The idea of separating them is to make code better and cleaner. The logic you build around them is your deal.
Usage:
Front:
Include the front-end lib.The lib is placed in the /lib folder:
Init the socket. You may pass port as a parameter. The default port used is 8081.
var socket = optionalPort
Using send methods(get, post, put, delete, notify) has same interface.
socketmethodNameeventName data callback
All arguments are optional instead of eventName.
socketsocketsocketsocket// Using notify for small messages looks good ideasocketsocketsocket
Server can send notifications too. To make it easier, the server sends only the name of the event. How you handle it on front:
socket
Also, using method 'on', you can set handler to the 'open' event of the socket. Its reserved word. 'Open' event fires when the socket connection between server and client is established and ready to function normally. Example:
socket
Or you can simply react on the certain events:
socket
You also may delete handlers of the server events dynamically using method "remove":
socket
Back:
The model of interaction looks like: Event(route, url) - Handler - Callback
The handler is actually callback too. Just not to get confused, we will call it handler. So, handler is actually the event handler on back-end, same as common router handler. Firing callback - is sending data/notification to front-end.
Include this module by:
npm install --save socket-event
Init socket server. Three possible ways to do that: pass port, pass server, dont pass any:
const s =// Example: set connection port to 8000var options = port : 8000// Other example: set connection to the created before http servervar options = server : server// This will set to default port 8081var options = nulls
Set handlers. Callback has two "node-way" arguments: error, data.
s
You might need to delete handler dynamically. Use 'remove' method:
s;s;s;s;s;
The server to client communication is done through the "notifyAll" method. This code notifies all connected clients about event.
s
Happens, that you need to get the original socket object. You may access it with method "getSocket".
let socket = s// Maybe atach some user object, session or any other logic