LuaSocket (UDP) 不接收数据报 [英] LuaSocket (UDP) not receiving datagrams
问题描述
我正在为我正在进行的一个项目试验 LuaSocket.我选择了 UDP 作为我的协议.
I'm experimenting with LuaSocket for a project I'm working on. I've chosen UDP as my protocol.
在网上寻找文档和教程,我尝试创建一个用于测试和学习的客户端-服务器对.
Looking for docs and tutorials online, I've attempted to create a client-server pair for testing and learning.
根据我所读到的内容,以下代码应该可以工作.但是,似乎只有服务器工作正常.客户端发送消息,但不会收到服务器的回复.
According to what I've read, the following code should work. However, only the server seems to be working properly. The client sends a message, but it will not receive the reply from the server.
感谢您提供任何帮助.
服务器:
-- Server
#!/usr/bin/env lua5.1
local socket = require("socket")
udp = socket.udp()
udp:setsockname("*", 53474)
udp:settimeout(0)
while true do
data, ip, port = udp:receivefrom()
if data then
print("Received: ", data, ip, port)
udp:sendto(data, ip, port)
end
socket.sleep(0.01)
end
客户:
-- Client
#!/usr/bin/env lua5.1
local socket = require("socket")
udp = socket.udp()
udp:setpeername("127.0.0.1", 53474)
udp:settimeout(0)
udp:send("Data!")
data = udp:receive()
if data then
print("Received: ", data)
end
推荐答案
你设置的超时值为0
,导致每次客户端超时.
The timeout value you set is 0
, which causes the client timeout every time.
要修复它,给它一个正超时值:
To fix it, give it a positive timeout value:
udp:settimeout(1)
或者将其设置为 nil
或一个负值,从而无限期地阻塞:
Or set it to nil
or a negative value, so it blocks indefinitely:
udp:settimeout()
或
udp:settimeout(-1)
这篇关于LuaSocket (UDP) 不接收数据报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!