【问题标题】:copas looping issue while connecting the server连接服务器时出现 copas 循环问题
【发布时间】:2017-03-22 18:55:02
【问题描述】:

我是 lua 编程新手,并尝试在 openwrt 中作为客户端实现 Lua-websocket。 here is the library. 试图使用客户端 copas 库,但问题是脚本在执行一次后停止监听服务器(即连接到服务器、接收消息、发送消息)。我希望脚本始终在没有任何超时或脚本停止的情况下监听服务器。 下面是脚本

local copas = require'copas'
local websocket = require'websocket'
local json = require('json')
local client = require 'websocket.client'.new()

local ok,err = client:connect('ws://192.168.1.250:8080')
if not ok then
   print('could not connect',err)
end

local ap_mac = { command = 'subscribe', channel = 'test' }
local ok = client:send(json.encode(ap_mac))
if ok then
   print('msg sent')
else
   print('connection closed')
end

local message,opcode = client:receive()
if message then
   print('msg',message,opcode)
else
   print('connection closed')
end

local replymessage = { command = 'message', message = 'TEST' }
local ok = client:send(json.encode(replymessage))
if ok then
   print('msg sent')
else
   print('connection closed')
end

copas.loop()

这里 copas.loop() 不起作用。

在 openWrt 上我安装了 lua 5.1

【问题讨论】:

    标签: websocket lua openwrt


    【解决方案1】:

    简答:你没有正确使用 Copas。

    详细说明: copas.loop 什么都不做,因为您既没有创建 Copas 服务器,也没有创建 Copas 线程。检查the Copas documentation

    脚本中的sendreceive 操作在 Copas 之外执行,因为它们不在Copas.addthread (function () ... end) 内。您还创建了一个 websocket 客户端,它不是 copas 客户端,而是同步客户端(默认设置)。检查the lua-websocket documentation 及其示例。

    解决办法:

    local copas     = require'copas'
    local websocket = require'websocket'
    local json      = require'cjson'
    
    local function loop (client)
      while client.state == "OPEN" do
        local message, opcode = client:receive()
        ... -- handle message
        local replymessage = { command = 'message', message = 'TEST' }
        local ok, err = client:send(json.encode(replymessage))
        ... -- check ok, err
      end
    end
    
    local function init ()
      local client = websocket.client.copas ()
      local ok,err = client:connect('ws://192.168.1.250:8080')
      ... -- check ok, err
      local ap_mac = { command = 'subscribe', channel = 'test' }
      ok, err = client:send(json.encode(ap_mac))
      ... -- check ok, err
      copas.addthread (function ()
        loop (client)
      end)
    end
    
    copas.addthread (init)
    copas.loop()
    

    init 函数为 Copas 实例化 client。它还在 Copas 线程中启动主 loop,只要连接打开,它就会等待传入消息。

    在启动 Copas 循环之前,请不要忘记为 init 函数添加 Copas 线程。

    【讨论】:

    • 嘿@AlbanLinard 谢谢你的帮助。它在 openwrt 上确实对我有用,也通过了 copas 文档;我完全搞砸了:P 感谢您纠正我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 2010-12-11
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    相关资源
    最近更新 更多