cws
Cross-platform interface for websockets
Install
npm install --save cws
API
For node usage, look at the ws package as that's what's returned.
src/browser.js can either be loaded directly or you can
require the module through browserify. Creating a server is not
supported in the browser. Arguments to the constructor are passed directly to
WebSocket & this module wraps around it to provide a node-style
api.
Browser
const CWS = require('cws');
const ws = CWS('ws://server/path', options);
console.log('readyState:', ws.readyState);
ws.on('error', e => {
console.error(e);
});
ws.on('close', e => {
console.log('The websocket was closed');
});
ws.on('message', message => {
if ('string' !== typeof message) throw Error("Message could not be decoded");
const received = JSON.parse(message);
console.log('Message received:', received);
});
ws.on('open', () => {
ws.send(JSON.stringify({
type: 'Greeting',
data: 'Hello World',
});
setTimeout(() => {
ws.close();
}, 5000);
});