wx.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. 'use strict'
  2. /* global wx */
  3. var socketOpen = false
  4. var socketMsgQueue = []
  5. function sendSocketMessage (msg) {
  6. if (socketOpen) {
  7. wx.sendSocketMessage({
  8. data: msg.buffer || msg
  9. })
  10. } else {
  11. socketMsgQueue.push(msg)
  12. }
  13. }
  14. function WebSocket (url, protocols) {
  15. var ws = {
  16. OPEN: 1,
  17. CLOSING: 2,
  18. CLOSED: 3,
  19. readyState: socketOpen ? 1 : 0,
  20. send: sendSocketMessage,
  21. close: wx.closeSocket,
  22. onopen: null,
  23. onmessage: null,
  24. onclose: null,
  25. onerror: null
  26. }
  27. wx.connectSocket({
  28. url: url,
  29. protocols: protocols
  30. })
  31. wx.onSocketOpen(function (res) {
  32. ws.readyState = ws.OPEN
  33. socketOpen = true
  34. for (var i = 0; i < socketMsgQueue.length; i++) {
  35. sendSocketMessage(socketMsgQueue[i])
  36. }
  37. socketMsgQueue = []
  38. ws.onopen && ws.onopen.apply(ws, arguments)
  39. })
  40. wx.onSocketMessage(function (res) {
  41. ws.onmessage && ws.onmessage.apply(ws, arguments)
  42. })
  43. wx.onSocketClose(function () {
  44. ws.onclose && ws.onclose.apply(ws, arguments)
  45. ws.readyState = ws.CLOSED
  46. socketOpen = false
  47. })
  48. wx.onSocketError(function () {
  49. ws.onerror && ws.onerror.apply(ws, arguments)
  50. ws.readyState = ws.CLOSED
  51. socketOpen = false
  52. })
  53. return ws
  54. }
  55. var websocket = require('websocket-stream')
  56. function buildUrl (opts, client) {
  57. var protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
  58. var url = protocol + '://' + opts.hostname + opts.path
  59. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  60. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  61. }
  62. if (typeof (opts.transformWsUrl) === 'function') {
  63. url = opts.transformWsUrl(url, opts, client)
  64. }
  65. return url
  66. }
  67. function setDefaultOpts (opts) {
  68. if (!opts.hostname) {
  69. opts.hostname = 'localhost'
  70. }
  71. if (!opts.path) {
  72. opts.path = '/'
  73. }
  74. if (!opts.wsOptions) {
  75. opts.wsOptions = {}
  76. }
  77. }
  78. function createWebSocket (client, opts) {
  79. var websocketSubProtocol =
  80. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  81. ? 'mqttv3.1'
  82. : 'mqtt'
  83. setDefaultOpts(opts)
  84. var url = buildUrl(opts, client)
  85. return websocket(WebSocket(url, [websocketSubProtocol]))
  86. }
  87. function buildBuilder (client, opts) {
  88. opts.hostname = opts.hostname || opts.host
  89. if (!opts.hostname) {
  90. throw new Error('Could not determine host. Specify host manually.')
  91. }
  92. return createWebSocket(client, opts)
  93. }
  94. module.exports = buildBuilder