tcpsrv.lua 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. local libnet = require "libnet"
  2. --下面演示用阻塞方式做自动应答服务器,只适合W5500
  3. local dName = "D2_TASK"
  4. local function netCB(msg)
  5. log.info("未处理消息", msg[1], msg[2], msg[3], msg[4])
  6. end
  7. local function serTask(port, adapter)
  8. log.info("tcpsrv", "准备监听端口", socket.localIP(adapter), port)
  9. local tx_buff = zbuff.create(1024)
  10. local rx_buff = zbuff.create(1024)
  11. local netc
  12. local result, param, succ, rIP, rPort
  13. netc = socket.create(adapter, dName)
  14. socket.debug(netc, true)
  15. socket.config(netc, port)
  16. while true do
  17. log.info(rtos.meminfo("sys"))
  18. result = libnet.waitLink(dName, 0, netc)
  19. result = libnet.listen(dName, 0, netc)
  20. if result then
  21. result,_ = socket.accept(netc, nil) --W5500的硬件协议栈不支持一对多
  22. if result then
  23. log.info("客户端连上了")
  24. libnet.tx(dName, 0, netc, "helloworld")
  25. end
  26. end
  27. while result do
  28. succ, param, rIP, rPort = socket.rx(netc, rx_buff)
  29. if not succ then
  30. log.info("客户端断开了", succ, param, rIP, port)
  31. break
  32. end
  33. if rx_buff:used() > 0 then
  34. log.info("收到客户端数据,长度", rx_buff:used())
  35. tx_buff:copy(nil,rx_buff) --把接收的数据返回给客户端
  36. rx_buff:del()
  37. end
  38. if tx_buff:used() > 0 then
  39. result, param = libnet.tx(dName, 5000, netc, tx_buff)
  40. end
  41. if not result then
  42. log.info("发送失败了", result, param)
  43. break
  44. end
  45. tx_buff:del()
  46. if tx_buff:len() > 1024 then
  47. tx_buff:resize(1024)
  48. end
  49. if rx_buff:len() > 1024 then
  50. rx_buff:resize(1024)
  51. end
  52. log.info(rtos.meminfo("sys"))
  53. result, param = libnet.wait(dName, 5000, netc)
  54. if not result then
  55. log.info("客户端断开了", result, param)
  56. break
  57. end
  58. end
  59. libnet.close(dName, 5000, netc)
  60. log.info(rtos.meminfo("sys"))
  61. sys.wait(1000)
  62. end
  63. end
  64. function SerDemo(port, adapter)
  65. sysplus.taskInitEx(serTask, dName, netCB, port, adapter)
  66. end