client_with_proxy.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict'
  2. var mqtt = require('mqtt')
  3. var HttpsProxyAgent = require('https-proxy-agent')
  4. var url = require('url')
  5. /*
  6. host: host of the endpoint you want to connect e.g. my.mqqt.host.com
  7. path: path to you endpoint e.g. '/foo/bar/mqtt'
  8. */
  9. var endpoint = 'wss://<host><path>'
  10. /* create proxy agent
  11. proxy: your proxy e.g. proxy.foo.bar.com
  12. port: http proxy port e.g. 8080
  13. */
  14. var proxy = process.env.http_proxy || 'http://<proxy>:<port>'
  15. var parsed = url.parse(endpoint)
  16. var proxyOpts = url.parse(proxy)
  17. // true for wss
  18. proxyOpts.secureEndpoint = parsed.protocol ? parsed.protocol === 'wss:' : true
  19. var agent = new HttpsProxyAgent(proxyOpts)
  20. var wsOptions = {
  21. agent: agent
  22. // other wsOptions
  23. // foo:'bar'
  24. }
  25. var mqttOptions = {
  26. keepalive: 60,
  27. reschedulePings: true,
  28. protocolId: 'MQTT',
  29. protocolVersion: 4,
  30. reconnectPeriod: 1000,
  31. connectTimeout: 30 * 1000,
  32. clean: true,
  33. clientId: 'testClient',
  34. wsOptions: wsOptions
  35. }
  36. var client = mqtt.connect(parsed, mqttOptions)
  37. client.on('connect', function () {
  38. console.log('connected')
  39. })
  40. client.on('error', function (a) {
  41. console.log('error!' + a)
  42. })
  43. client.on('offline', function (a) {
  44. console.log('lost connection!' + a)
  45. })
  46. client.on('close', function (a) {
  47. console.log('connection closed!' + a)
  48. })
  49. client.on('message', function (topic, message) {
  50. console.log(message.toString())
  51. })