Skip to content

Instantly share code, notes, and snippets.

@xfguo
Created April 12, 2014 16:06
Show Gist options
  • Save xfguo/10543290 to your computer and use it in GitHub Desktop.
Save xfguo/10543290 to your computer and use it in GitHub Desktop.
Added UDP server example powered by luaevent.
-- udp-client test
-- based on code from http://blog.chinaunix.net/uid-27194309-id-3499261.htmlEF
local socket = require "socket"
local address = "127.0.0.1"
local port = 8080
local udp = socket.udp()
udp:settimeout(0)
udp:setpeername(address, port)
--udp:sendto("udp-test", address, port)
udp:send("udp-test0n")
udp:send("udp-test1n")
udp:send("udp-test2n")
print "Thank you."
-- udp-server test with luaevent
-- based on code from http://blog.chinaunix.net/uid-27194309-id-3499261.htmlEF
-- try to use luaevent.core but not luaevent copas style api
--
-- modified by Xiongfei Guo <xfguo@credosemi.com>
local socket = require "socket"
local luaevent = require "luaevent"
local core = luaevent.core
local port = 8080
local udp = socket.udp()
base = core.new()
udp:settimeout(0)
udp:setsockname('*', port)
local data, msg_or_ip, port_or_nil
local running = true
-- the beginning of the loop proper...
print "Beginning server loop."
function cb(event)
data, msg_or_ip, port_or_nil = udp:receivefrom()
if data then
print("udp:receivefrom: " .. data .. msg_or_ip, port_or_nil)
udp:sendto(data, msg_or_ip, port_or_nil)
if data == "quit" then
running = false
end
elseif msg_or_ip ~= 'timeout' then
error("Unknown network error: "..tostring(msg))
end
end
base:addevent(udp, core.EV_READ, cb)
base:loop()
print "Thank you."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment