wsocket
v1.0.1
Published
Simple wrapper of web socket on website.
Downloads
2
Readme
wsocket
Simple wrapper of web socket on website.
Include
<script src="node_modules/web-module/web-module.js"></script>
<script src="node_modules/wsocket/wsocket.js"></script>
Usage
const wsocket = module.require('wsocket');
let ws = wsocket('/web/socket/uri');
ws.onOpen((event)=>{
// Do something
}).onError((event)=>{
// Do something
}).onMessage((event)=>{
// Do something
}).onData((data)=>{
// Do something with raw data
}).onJsonData((data)=>{
// Do something with json data
});
Events
onOpen(f, context)
Parameters:
- f function(event)
- context object (optional)
Example:
ws.onOpen((event)=>{
// Do something
}, context);
onError(f, context)
Parameters:
- f function(event)
- context object (optional)
Examples:
ws.onError((event)=>{
// Do something
}, context);
onMessage(f, context)
Parameters:
- f function(event)
- context object (optional)
Examples:
ws.onMessage((event)=>{
// Do something
}, context);
onData(f, context)
Parameters:
- f function(data)
- context object (optional)
Examples:
ws.onData((data)=>{
// Do something with raw data
}, context);
onJsonData(f, context)
Parameters:
- f function(data)
- context object (optional)
Examples:
ws.onJsonData((data)=>{
// Do something with json data
}, context);
onClose(f, context)
Parameters:
- f function(event)
- context object (optional)
Examples:
ws.onClose((event)=>{
// Do something
}, context);
Ready state
isConnecting()
Check if the websocket is on CONNECTING state.
isOpen()
Check if the websocket is on OPEN state.
isClosing()
Check if the websocket is on CLOSING state.
isClosed()
Check if the websocket is on CLOSED state.
readyState()
Get websocket ready state.
Others
open(uri)
Open websocket with other uri.
close()
Close current websocket.
reopenOnClose()
Set up websocket to automatically reopen when closed.
Examples:
let ws = wsocket('/web/socket/uri').reopenOnClose();
reopenIfClosed()
Reopen current websocket if closed.
send(message)
Parameters:
- message string | object | mixed
Examples:
// Send string
ws.send('some string');
// Send json data
ws.send({
item: 'some data',
another: 'another data'
});
// Other types of data will be convert to string
ws.send(12345);
Bugs or feature requests
Please contact to email