1.0.1 • Published 7 years ago
@arnellebalane/websockets v1.0.1
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/websocketsUsage
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.Serverobject, and theoptionsparameter passed to it is just passed directory to thews.Serverconstructor. Refer to thewsdocs for what options you can use.
socket- A wrapper around the native
Socketobject 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
namewill be emitted on the client and the callback receivesdata. - If called on the client, an event called
namewill 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
dataobject from thesocket.emitcall.
- A wrapper around the native
License
MIT License