我是lua编程新手,正在尝试将Lua-websocket作为客户端在openwrt中实现。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上,我安装了Lua5.1
发布于 2017-03-22 18:55:03
简而言之:您没有正确使用Copas。
详细地说:copas.loop什么也不做,因为您既没有创建Copas服务器,也没有创建Copas线程。检查the Copas documentation。
脚本中的send和receive操作在 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线程。do not忘记添加一个Copas线程。
https://stackoverflow.com/questions/42945538
复制相似问题