@arnellebalane/websockets
v1.0.1
Published
A socket.io-like WebSocket server and client library on top of ws.
Downloads
7
Readme
websockets
A WebSocket server and client library built on top of ws
with a similar
event-based mechanism to socket.io
.
Installing
npm install @arnellebalane/websockets
Usage
On the server:
import websockets from '@arnellebalane/websockets';
const ws = websockets({
server, // An http.Server object
path: '/ws'
});
ws.on('connection', socket => {
socket.emit('greeting', 'Hello there!');
socket.on('message', data => {
// message === [1, 2, 3]
});
});
If you are using the usual require()
, you can load this package through:
const websockets = require('@arnellebalane/websockets').default;
On the client:
import websockets from '@arnellebalane/websockets/client';
const socket = websockets('ws://hostname/ws');
socket.on('greeting', data => {
// data === 'Hello there!';
socket.emit('message', [1, 2, 3]);
});
API
websockets(options)
- Factory method for creating a new WebSocket server.
- Under the hood it just creates a new
ws.Server
object, and theoptions
parameter passed to it is just passed directory to thews.Server
constructor. Refer to thews
docs for what options you can use.
socket
- A wrapper around the native
Socket
object representing the WebSocket connection, adding extra methods to make the event-based API possible. socket.emit(name, data)
- If called on the server, an event called
name
will be emitted on the client and the callback receivesdata
. - If called on the client, an event called
name
will be emitted on the server and the callback receivesdata
. name
(String): The name of the event.data
(Any): Needs to be a JSON-serializable object.
- If called on the server, an event called
socket.on(name, callback)
name
(String): The name of the event to listen to.callback
(Function)- The function to execute when the event is emitted.
- Receives the
data
object from thesocket.emit
call.
- A wrapper around the native
License
MIT License