parent
3ada8f4c8e
commit
4f0ebc3870
|
@ -1,26 +1,27 @@
|
||||||
import { Socket } from '../src'
|
import Socket from '../src'
|
||||||
|
|
||||||
async function packetProcess (packet) {
|
async function packetProcess(packet) {
|
||||||
return new Promise(resolve => {
|
return new Promise(resolve => {
|
||||||
let res = {}
|
let res = {}
|
||||||
|
console.log('processing')
|
||||||
if (packet.cmd !== 'doit') {
|
if (packet.cmd !== 'doit') {
|
||||||
res.response = `the payload sent was: ${packet.payload} with command ${packet.cmd}`
|
res.response = `command ${packet.cmd} was unknown at server echo payload back`
|
||||||
|
res.payload = packet.payload
|
||||||
|
console.log(JSON.stringify(res))
|
||||||
} else {
|
} else {
|
||||||
res.cmd = 'doit'
|
res.cmd = 'doit'
|
||||||
res.response = 'take some action in browser like color a button green' }
|
res.response = 'take some action in browser like color a button green'
|
||||||
resolve (res)
|
res.payload = {button:'on'}
|
||||||
|
}
|
||||||
|
resolve(res)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// let test = new Test()
|
// let test = new Test()
|
||||||
let test = new Socket({port:8090, clientTracking:true})
|
let test = new Socket({ port: 8090, clientTracking: true })
|
||||||
test.registerPacketProcessor(packetProcess)
|
test.registerPacketProcessor(packetProcess)
|
||||||
|
;(async () => {
|
||||||
;
|
|
||||||
(async () => {
|
|
||||||
|
|
||||||
console.log(await test.create())
|
console.log(await test.create())
|
||||||
|
|
||||||
})().catch(err => {
|
})().catch(err => {
|
||||||
console.error('FATAL: UNABLE TO START SYSTEM!\n',err)
|
console.error('FATAL: UNABLE TO START SYSTEM!\n', err)
|
||||||
})
|
})
|
||||||
|
|
14
package.json
14
package.json
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "@uci/websocket",
|
"name": "@uci/websocket",
|
||||||
"version": "0.1.9",
|
"version": "0.3.0",
|
||||||
"description": "JSON packet host websocket server",
|
"description": "JSON packet host websocket server",
|
||||||
"main": "src",
|
"main": "src",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
@ -32,19 +32,19 @@
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/uCOMmandIt/websocket#readme",
|
"homepage": "https://github.com/uCOMmandIt/websocket#readme",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"chai": "^4.1.2",
|
"chai": "^4.2.0",
|
||||||
"chai-as-promised": "^7.1.1",
|
"chai-as-promised": "^7.1.1",
|
||||||
"codecov": "^3.0.0",
|
"codecov": "^3.1.0",
|
||||||
"esm": "^3.0.34",
|
"esm": "^3.0.84",
|
||||||
"istanbul": "^0.4.5",
|
"istanbul": "^0.4.5",
|
||||||
"mocha": "^5.0.1",
|
"mocha": "^5.0.1",
|
||||||
"nodemon": "^1.15.1"
|
"nodemon": "^1.18.6"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@uci/logger": "0.0.3",
|
"@uci/logger": "0.0.6",
|
||||||
"better-try-catch": "^0.6.2",
|
"better-try-catch": "^0.6.2",
|
||||||
"clone": "^2.1.1",
|
"clone": "^2.1.1",
|
||||||
"death": "^1.1.0",
|
"death": "^1.1.0",
|
||||||
"ws": "^5.1.1"
|
"ws": "^6.1.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
import Socket from './socket'
|
import Socket from './socket'
|
||||||
|
|
||||||
export { Socket as Socket }
|
export { Socket as WebSocket }
|
||||||
export default Socket
|
export default Socket
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
|
|
||||||
import WebSocket from 'ws'
|
import WebSocket from 'ws'
|
||||||
import btc from 'better-try-catch'
|
import btc from 'better-try-catch'
|
||||||
import _ON_DEATH from 'death' //this is intentionally ugly
|
import _ON_DEATH from 'death' //this is intentionally ugly
|
||||||
|
@ -7,26 +6,34 @@ import clone from 'clone'
|
||||||
import logger from '@uci/logger'
|
import logger from '@uci/logger'
|
||||||
let log = {}
|
let log = {}
|
||||||
|
|
||||||
export default class Socket extends WebSocket.Server {
|
/**
|
||||||
constructor (opts = {}) {
|
* Socket - a websocket that supports uci packets
|
||||||
|
* @class WebSocket
|
||||||
|
* @extends ws.server
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
class Socket extends WebSocket.Server {
|
||||||
|
constructor(opts = {}) {
|
||||||
opts.host = opts.host || '0.0.0.0'
|
opts.host = opts.host || '0.0.0.0'
|
||||||
opts.port = opts.port || 8090
|
opts.port = opts.port || 8090
|
||||||
opts.clientTracking = opts.clientTracking || true
|
opts.clientTracking = opts.clientTracking || true
|
||||||
super(opts)
|
super(opts)
|
||||||
this.id = opts.id || opts.name || 'Websocket:'+ new Date().getTime()
|
this.id = opts.id || opts.name || 'Websocket:' + new Date().getTime()
|
||||||
this.opts = opts // for use to recover from selected errors
|
this.opts = opts // for use to recover from selected errors
|
||||||
//self bindings
|
//self bindings
|
||||||
this._listen = this._listen.bind(this)
|
this._listen = this._listen.bind(this)
|
||||||
this.create = this.create.bind(this)
|
this.create = this.create.bind(this)
|
||||||
log = logger({file:'src/socket.js',class:'Socket',name:'websocket',id:this.id})
|
log = logger({
|
||||||
|
file: 'src/socket.js',
|
||||||
|
class: 'Socket',
|
||||||
|
name: 'websocket',
|
||||||
|
id: this.id
|
||||||
|
})
|
||||||
} // end constructor
|
} // end constructor
|
||||||
|
|
||||||
async create () {
|
async create() {
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
|
_ON_DEATH(async () => {
|
||||||
_ON_DEATH( async () => {
|
|
||||||
log.info('\nhe\'s dead jim')
|
log.info('\nhe\'s dead jim')
|
||||||
await this._destroy()
|
await this._destroy()
|
||||||
})
|
})
|
||||||
|
@ -35,7 +42,7 @@ export default class Socket extends WebSocket.Server {
|
||||||
process.kill(process.pid, 'SIGUSR2')
|
process.kill(process.pid, 'SIGUSR2')
|
||||||
})
|
})
|
||||||
|
|
||||||
this.on('error', async (err) => {
|
this.on('error', async err => {
|
||||||
log.fatal(err, 'socket server error')
|
log.fatal(err, 'socket server error')
|
||||||
console.error(err, 'socket server error')
|
console.error(err, 'socket server error')
|
||||||
reject(err)
|
reject(err)
|
||||||
|
@ -44,57 +51,62 @@ export default class Socket extends WebSocket.Server {
|
||||||
this.on('listening', async () => {
|
this.on('listening', async () => {
|
||||||
this._listen()
|
this._listen()
|
||||||
log.info('websocket server created and listening at', this.address())
|
log.info('websocket server created and listening at', this.address())
|
||||||
resolve(`websocket ready and listening at ${this.address().address}:${this.address().port}`)
|
resolve(
|
||||||
|
`websocket ready and listening at ${this.address().address}:${
|
||||||
|
this.address().port
|
||||||
|
}`
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
} // end create
|
} // end create
|
||||||
|
|
||||||
registerPacketProcessor (func) {
|
registerPacketProcessor(func) {
|
||||||
this._packetProcess = func
|
this._packetProcess = func
|
||||||
}
|
}
|
||||||
|
|
||||||
_listen () {
|
_listen() {
|
||||||
|
|
||||||
this.on('connection', async (socket, req) => {
|
this.on('connection', async (socket, req) => {
|
||||||
let send = this._send.bind(socket)
|
let send = this._send.bind(socket)
|
||||||
log.info({req:req},'new consumer connecting')
|
log.info({ req: req }, 'new consumer connecting')
|
||||||
socket.address = req.remoteAddress
|
socket.address = req.remoteAddress
|
||||||
socket.on('message', messageProcess.bind(this,socket))
|
socket.on('message', messageProcess.bind(this, socket))
|
||||||
|
|
||||||
async function messageProcess (client,strPacket) {
|
async function messageProcess(client, strPacket) {
|
||||||
log.info({packet:strPacket},' incoming packet on web socket side')
|
log.info({ packet: strPacket }, ' incoming packet on web socket side')
|
||||||
let res = {}
|
let res = {}
|
||||||
let [err, packet] = btc(JSON.parse)(strPacket)
|
let [err, packet] = btc(JSON.parse)(strPacket)
|
||||||
log.info('packet', err, packet)
|
log.info('packet', err, packet)
|
||||||
if (err) { res = {error: `Could not parse JSON: ${packet}`} }
|
if (err) {
|
||||||
else {
|
res = { error: `Could not parse JSON: ${packet}` }
|
||||||
|
} else {
|
||||||
if (packet.clientID) {
|
if (packet.clientID) {
|
||||||
client.ID = packet.clientID
|
client.ID = packet.clientID
|
||||||
res.cmd='ackID'
|
res.cmd = 'ackID'
|
||||||
|
} else {
|
||||||
|
res = (await this._packetProcess(clone(packet))) || {}
|
||||||
|
if (Object.keys(res).length === 0)
|
||||||
|
res = {
|
||||||
|
error:
|
||||||
|
'socket packet command function likely did not return a promise',
|
||||||
|
packet: packet
|
||||||
}
|
}
|
||||||
else {
|
|
||||||
res = await this._packetProcess(clone(packet)) || {}
|
|
||||||
if (Object.keys(res).length === 0) res = { error: 'socket packet command function likely did not return a promise', packet:packet}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (packet) {
|
if (packet) {
|
||||||
res._header = clone(packet._header,false) || {} //make sure return packet has header with id in case it was removed in processing
|
res._header = clone(packet._header, false) || {} //make sure return packet has header with id in case it was removed in processing
|
||||||
delete packet._header // remove before adding to response header as request
|
delete packet._header // remove before adding to response header as request
|
||||||
} else res._header = {}
|
} else res._header = {}
|
||||||
res._header.request = clone(packet,false)
|
res._header.request = clone(packet, false)
|
||||||
res._header.responder = {name:this.name,instanceID:this.id}
|
res._header.responder = { name: this.name, instanceID: this.id }
|
||||||
res._header.socket = this.address()
|
res._header.socket = this.address()
|
||||||
if (!res.cmd) res.cmd = 'reply' // by default return command is 'reply'
|
if (!res.cmd) res.cmd = 'reply' // by default return command is 'reply'
|
||||||
log.info({packet:res},await send(res))
|
log.info({ packet: res }, await send(res))
|
||||||
}
|
}
|
||||||
|
|
||||||
}) // end connected consumer
|
}) // end connected consumer
|
||||||
log.info('socket created')
|
log.info('socket created')
|
||||||
} // end listen
|
} // end listen
|
||||||
|
|
||||||
async _destroy () {
|
async _destroy() {
|
||||||
log.info('closing down socket')
|
log.info('closing down socket')
|
||||||
await this.close()
|
await this.close()
|
||||||
log.info('all connections closed....exiting')
|
log.info('all connections closed....exiting')
|
||||||
|
@ -102,29 +114,32 @@ export default class Socket extends WebSocket.Server {
|
||||||
}
|
}
|
||||||
|
|
||||||
// default packet process, just a simple echo - replace
|
// default packet process, just a simple echo - replace
|
||||||
async _packetProcess (packet) {
|
async _packetProcess(packet) {
|
||||||
return new Promise(resolve => {
|
return new Promise(resolve => {
|
||||||
resolve(packet)
|
resolve(packet)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async push (packet,id) {
|
async push(packet, id) {
|
||||||
this.clients.forEach(async (client) => {
|
packet._header = { id: id || 'pushed' }
|
||||||
|
this.clients.forEach(async client => {
|
||||||
if (client.readyState === WebSocket.OPEN) {
|
if (client.readyState === WebSocket.OPEN) {
|
||||||
if (!id || id ===client.ID ) await this._send.bind(client)(packet)
|
if (!id || id === client.ID) await this._send.bind(client)(packet)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// must have a consumer socket instance bound to call this function
|
// must have a consumer socket instance bound to call this function
|
||||||
async _send (packet) {
|
async _send(packet) {
|
||||||
return new Promise( (resolve,reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
if (this.readyState !== 1 ) reject (`Connection not Ready, CODE:${this.readyState}`)
|
if (this.readyState !== 1)
|
||||||
let [err,message] = btc(JSON.stringify)(packet)
|
reject(`Connection not Ready, CODE:${this.readyState}`)
|
||||||
|
let [err, message] = btc(JSON.stringify)(packet)
|
||||||
if (err) reject(`Could not JSON stringify: ${packet}`)
|
if (err) reject(`Could not JSON stringify: ${packet}`)
|
||||||
this.send(message)
|
this.send(message)
|
||||||
resolve('sent packet')
|
resolve('sent packet')
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
} // end class
|
} // end class
|
||||||
|
|
||||||
|
export default Socket
|
||||||
|
|
Loading…
Reference in New Issue