CF web Websocket應(yīng)用指南

2019-04-02 11:28 更新

介紹

  1. Websocket什么? WebSocket是一種在單個TCP連接上進(jìn)行全雙工通信的協(xié)議。WebSocket通信協(xié)議于2011年被IETF定為標(biāo)準(zhǔn)RFC 6455,并由RFC7936補充規(guī)范。WebSocket API也被W3C定為標(biāo)準(zhǔn)。


WebSocket使得客戶端和服務(wù)器之間的數(shù)據(jù)交換變得更加簡單,允許服務(wù)端主動向客戶端推送數(shù)據(jù)。在WebSocket API中,瀏覽器和服務(wù)器只需要完成一次握手,兩者之間就直接可以創(chuàng)建持久性的連接,并進(jìn)行雙向數(shù)據(jù)傳輸。

使用

  1. cfwebsocket協(xié)議層實現(xiàn)將其作為一種升級協(xié)議內(nèi)嵌到httpd庫內(nèi). 所以, 當(dāng)您使用httpd庫的時候即可很方便的使用websocket.

  1. 首先, 我們根據(jù)[cf web的初始化與使用](https://github.com/CandyMi/core_framework/wiki/QuickStart)最后的示例, 在```script/main.lua```文件內(nèi)添加一段代碼:

  1. app:ws('/ws', require 'ws')

  1. 然后我們在```script```目錄建立一個```ws.lua```文件, 在其內(nèi)部添加如下代碼:

  1. local class = require "class"
  2. local timer = require 'internal.Timer'
  3. local json = require "json"
  4. local MQ = require "MQ"
  5. local websocket = class("websocket")
  6. function websocket:ctor(opt)
  7. self.ws = opt.ws -- websocket對象
  8. self.send_masked = false -- 掩碼(默認(rèn)為false, 不建議修改或者使用)
  9. self.max_payload_len = 65535 -- 最大有效載荷長度(默認(rèn)為65535, 不建議修改或者使用)
  10. self.timeout = 15
  11. self.count = 0
  12. self.mq = MQ:new({host = 'localhost', port = 6379, type = 'redis'})
  13. end
  14. function websocket:on_open()
  15. print('on_open')
  16. self.timer = timer.at(0.01, function ( ... ) -- 定時器
  17. self.count = self.count + 1
  18. self.ws:send(tostring(self.count))
  19. end)
  20. self.mq:on('/test/*', function (msg) -- 消息隊列
  21. if not msg then
  22. self.ws:send('{"code":500,"message":"無法連接到mq(reds)"}')
  23. return self.ws:close()
  24. end
  25. self.ws:send(json.encode(msg))
  26. end)
  27. end
  28. function websocket:on_message(data, typ)
  29. print('on_message', self.ws, data)
  30. self.ws:send('welcome')
  31. self.ws:close(data)
  32. end
  33. function websocket:on_error(error)
  34. print('on_error', self.ws, error)
  35. end
  36. function websocket:on_close(data)
  37. print('on_close', self.ws, data)
  38. if self.mq then -- 清理消息隊列
  39. self.mq:close()
  40. self.mq = nil
  41. end
  42. if self.timer then -- 清理定時器
  43. self.timer:stop()
  44. self.timer = nil
  45. end
  46. end
  47. return websocket

最后

上述所有代碼可以在script文件夾內(nèi)找到.

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號