连接服务器时出现copas循环问题

时间:2017-03-22 07:43:52

标签: websocket lua openwrt

我是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

1 个答案:

答案 0 :(得分:0)

简短回答:您没有正确使用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线程。

相关问题