CF web Websocket应用指南

2019-04-02 11:28 更新

介绍

Websocket什么? WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。


WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

使用

cf的websocket协议层实现将其作为一种升级协议内嵌到httpd库内. 所以, 当您使用httpd库的时候即可很方便的使用websocket.

首先, 我们根据[cf web的初始化与使用](https://github.com/CandyMi/core_framework/wiki/QuickStart)最后的示例, 在```script/main.lua```文件内添加一段代码:

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

然后我们在```script```目录建立一个```ws.lua```文件, 在其内部添加如下代码:

local class = require "class"
local timer = require 'internal.Timer'
local json = require "json"
local MQ = require "MQ"
local websocket = class("websocket")


function websocket:ctor(opt)
    self.ws = opt.ws             -- websocket对象
    self.send_masked = false     -- 掩码(默认为false, 不建议修改或者使用)
    self.max_payload_len = 65535 -- 最大有效载荷长度(默认为65535, 不建议修改或者使用)
    self.timeout = 15
    self.count = 0
    self.mq = MQ:new({host = 'localhost', port = 6379, type = 'redis'})
end


function websocket:on_open()
    print('on_open')
    self.timer = timer.at(0.01, function ( ... ) -- 定时器
        self.count = self.count + 1
        self.ws:send(tostring(self.count))
    end)
    self.mq:on('/test/*', function (msg) -- 消息队列
        if not msg then
            self.ws:send('{"code":500,"message":"无法连接到mq(reds)"}')
            return self.ws:close()
        end
        self.ws:send(json.encode(msg))
    end)
end


function websocket:on_message(data, typ)
    print('on_message', self.ws, data)
    self.ws:send('welcome')
    self.ws:close(data)
end


function websocket:on_error(error)
    print('on_error', self.ws, error)
end


function websocket:on_close(data)
    print('on_close', self.ws, data)
    if self.mq then     -- 清理消息队列
        self.mq:close()
        self.mq = nil
    end
    if self.timer then  -- 清理定时器
        self.timer:stop()
        self.timer = nil
    end
end


return websocket

最后

上述所有代码可以在script文件夹内找到.

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号