LuaSocket (UDP) not receiving datagrams

跟風遠走 提交于 2019-12-02 05:25:00

问题


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.

Thank you for any help anyone can provide.

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:

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

回答1:


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)

Or set it to nil or a negative value, so it blocks indefinitely:

udp:settimeout()

or

udp:settimeout(-1)


来源:https://stackoverflow.com/questions/28105571/luasocket-udp-not-receiving-datagrams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!