luasocket 之 udp

http://blog.chinaunix.net/uid-27194309-id-3499261.html  在页面的后面有


先在路由器上执行:

opkg install luasocket_2.0.2-3_ar71xx.ipk

udp server 例程如下:


点击(此处)折叠或打开

  1. -- upd-server Test
  2. local socket = require "socket"

  3. local port = 8080
  4. local udp = socket.udp()
  5. udp:settimeout(0)
  6. udp:setsockname('*', port)    --server

  7. local data, msg_or_ip, port_or_nil
  8. local running = true

  9. -- the beginning of the loop proper...
  10. print "Beginning server loop."
  11. while running do
  12.     data, msg_or_ip, port_or_nil = udp:receivefrom()
  13.     if data then
  14.             print("udp:receivefrom: " .. data .. msg_or_ip, port_or_nil)
  15.             udp:sendto(data, msg_or_ip, port_or_nil)

  16.             if data == "quit" then
  17.                 running = false
  18.             end
  19.     elseif msg_or_ip ~= 'timeout' then
  20.         error("Unknown network error: "..tostring(msg))
  21.     end

  22.     socket.sleep(0.01)
  23. end

  24. print "Thank you."


udp client 例程如下:


点击(此处)折叠或打开

  1. -- upd-client Test
  2. local socket = require "socket"

  3. local address = "192.168.1.224"
  4. local port = 8080
  5. local udp = socket.udp()

  6. udp:settimeout(0)
  7. udp:setpeername(address, port)
  8. --udp:sendto("udp-test", address, port)
  9. udp:send("udp-test0n")
  10. udp:send("udp-test1n")
  11. udp:send("udp-test2n")

  12. print "Thank you."



用udp实现更方便的调试


  1. -- luasocket upd-client Test
  2. local socket = require "socket"

  3. debug = 1
  4. function DEBUGP(str)
  5.     if debug == 1 then
  6.         local server_ip = "192.168.1.224"
  7.         local server_port = 8080
  8.         local udp = socket.udp()

  9.         udp:settimeout(0)
  10.         udp:setpeername(server_ip, server_port)
  11.         --udp:sendto("udp-test", address, port)
  12.         udp:send(str)
  13.         udp:close()
  14.         
  15.     elseif debug == 2 then
  16.         print(str)
  17.     end
  18. end

  19. local data1 = 101
  20. local data2 = 102
  21. local data3 = 103
  22. DEBUGP("test - " .. data1 .. "n")
  23. DEBUGP("test - " .. data2 .. "n")
  24. DEBUGP("test - " .. data3 .. "n")

  25. print "Thank you."

你可能感兴趣的:(lua)