codecamp

CF web Websocket应用指南

介绍

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文件夹内找到.

CF web的初始化与使用
CF web 中间件开发指南
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

API 使用手册

HTTP API

Mail API

DB API

DB

Cache API

class API

MQ API

MQ

Crypt API

cf API

cf

System API

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }