ctrl-socket
v0.0.1
Published
CtrlSocket.js is WebSocket client util and easy to use.
Downloads
3
Readme
CtrlSocket.js
Usage
Create
const url = 'wss://xxxxxxxxx' //websocket url const ws = new CtrlSocket(url)
Methods
subscribe
ws.subscribe({ onopen: function , onmessage: function, onerror: function, onclose: function })
Call back function , will call onmessage
ws.subscribe( (e)=>console.log(e.data) ) // same ws.subscribe({ onmessage: (e)=>console.log(e.data) })
Return CtrlSocket Object
retry
When websocket state is closed and closed code != 1000 will reconnect
ws.retry(count: Number,interval: Number)
retry(3, 1000) //reconnect to server 3 times per second retry(3) //reconnect to server 3 times (interval default value is 5 seconds) retry() //reconnect to server until server response
Return CtrlSocket Object
connect
connect to server , readyState changes to OPEN
ws.connect()
disconnect
disconnect , readyState changes to CLOSED
ws.disconnect()
reconnect
reconnect to server
ws.reconnect(code = 1000, reason = 'Normal closure')
send
send a message to server
ws.send('Hi there!') // String ws.send({ message: 'Hi there!' //Object })
readyState get websocket state
const state = ws.readyState
in Vue you can ...
... computed:{ getState(){ let msg ='' if(this.state===1){ msg = 'Open' } ... return msg } }, watch:{ state(newValue,oldValue){ //todo } }, created(){ ... this.ws = new CtrlSocket(url) this.state = this.ws.readyState } ...
heartBeat Check websocket still connect to server, if loss connection will call onclose.
ws.heartBeat(interval: Number, message)
interval--> default 30 seconds
// use with retry() ws.retry() .heartBeat(3000,{ comment: 'heartBeat' //if loss connection , reconnect until server response }) ws.heartBeat() //if loss connection do nothing , readyState = CLOSED
Return CtrlSocket Object
Example
const connectURL = 'wss://echo.websocket.org'
function onmessage (response) {
if (typeof response.data === 'string') {
// todo
}
}
const ws = new CtrlSocket(connectURL)
.heartBeat(60000,'ping')
.retry(3)
.subscribe({
onopen: () => console.log('OPEN') ,
onclose: () => console.log('CLOSED'),
onerror: () => console.log('Error')
onmessage
})