socketTask.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. --- 模块功能:socket长连接功能测试.
  2. -- 与服务器连接成功后
  3. --
  4. -- 每隔10秒钟发送一次"heart data\r\n"字符串到服务器
  5. --
  6. -- 每隔20秒钟发送一次"location data\r\n"字符串到服务器
  7. --
  8. -- 与服务器断开连接后,会自动重连
  9. -- @author openLuat
  10. -- @module socketLongConnection.testSocket1
  11. -- @license MIT
  12. -- @copyright openLuat
  13. -- @release 2018.03.27
  14. module(...,package.seeall)
  15. require"socket"
  16. require"socketOutMsg"
  17. require"socketInMsg"
  18. local ready = false
  19. --- socket连接是否处于激活状态
  20. -- @return 激活状态返回true,非激活状态返回false
  21. -- @usage socketTask.isReady()
  22. function isReady()
  23. return ready
  24. end
  25. --[[
  26. socket.setIpStatis(60)
  27. sys.subscribe("LIB_IP_STATIS_RPT", function(dataFlow)
  28. log.info("LIB_IP_STATIS_RPT dataFlow",dataFlow)
  29. end)
  30. ]]
  31. --启动socket客户端任务
  32. sys.taskInit(
  33. function()
  34. local retryConnectCnt = 0
  35. while true do
  36. if not socket.isReady() then
  37. retryConnectCnt = 0
  38. --等待网络环境准备就绪,超时时间是5分钟
  39. sys.waitUntil("IP_READY_IND",300000)
  40. end
  41. if socket.isReady() then
  42. --创建一个socket tcp客户端
  43. local socketClient = socket.tcp()
  44. --阻塞执行socket connect动作,直至成功
  45. if socketClient:connect("180.97.81.180","55859") then
  46. retryConnectCnt = 0
  47. ready = true
  48. socketOutMsg.init()
  49. --循环处理接收和发送的数据
  50. while true do
  51. if not socketInMsg.proc(socketClient) then log.error("socketTask.socketInMsg.proc error") break end
  52. if not socketOutMsg.proc(socketClient) then log.error("socketTask.socketOutMsg proc error") break end
  53. end
  54. socketOutMsg.unInit()
  55. ready = false
  56. else
  57. retryConnectCnt = retryConnectCnt+1
  58. end
  59. --断开socket连接
  60. socketClient:close()
  61. if retryConnectCnt>=5 then link.shut() retryConnectCnt=0 end
  62. sys.wait(5000)
  63. else
  64. --进入飞行模式,20秒之后,退出飞行模式
  65. net.switchFly(true)
  66. sys.wait(20000)
  67. net.switchFly(false)
  68. end
  69. end
  70. end
  71. )