Socket.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const ee = require('namespace-emitter')
  2. module.exports = class UppySocket {
  3. constructor (opts) {
  4. this.opts = opts
  5. this._queued = []
  6. this.isOpen = false
  7. this.emitter = ee()
  8. this._handleMessage = this._handleMessage.bind(this)
  9. this.close = this.close.bind(this)
  10. this.emit = this.emit.bind(this)
  11. this.on = this.on.bind(this)
  12. this.once = this.once.bind(this)
  13. this.send = this.send.bind(this)
  14. if (!opts || opts.autoOpen !== false) {
  15. this.open()
  16. }
  17. }
  18. open () {
  19. this.socket = new WebSocket(this.opts.target)
  20. this.socket.onopen = (e) => {
  21. this.isOpen = true
  22. while (this._queued.length > 0 && this.isOpen) {
  23. const first = this._queued[0]
  24. this.send(first.action, first.payload)
  25. this._queued = this._queued.slice(1)
  26. }
  27. }
  28. this.socket.onclose = (e) => {
  29. this.isOpen = false
  30. }
  31. this.socket.onmessage = this._handleMessage
  32. }
  33. close () {
  34. if (this.socket) {
  35. this.socket.close()
  36. }
  37. }
  38. send (action, payload) {
  39. // attach uuid
  40. if (!this.isOpen) {
  41. this._queued.push({ action, payload })
  42. return
  43. }
  44. this.socket.send(JSON.stringify({
  45. action,
  46. payload
  47. }))
  48. }
  49. on (action, handler) {
  50. this.emitter.on(action, handler)
  51. }
  52. emit (action, payload) {
  53. this.emitter.emit(action, payload)
  54. }
  55. once (action, handler) {
  56. this.emitter.once(action, handler)
  57. }
  58. _handleMessage (e) {
  59. try {
  60. const message = JSON.parse(e.data)
  61. this.emit(message.action, message.payload)
  62. } catch (err) {
  63. console.log(err)
  64. }
  65. }
  66. }