socket4G.lua 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. --- 模块功能:数据链路激活、SOCKET管理(创建、连接、数据收发、状态维护)
  2. -- @module socket
  3. -- @author openLuat
  4. -- @license MIT
  5. -- @copyright openLuat
  6. -- @release 2017.9.25
  7. require "link"
  8. require "utils"
  9. module(..., package.seeall)
  10. local sockets = {}
  11. -- 单次发送数据最大值
  12. local SENDSIZE = 11200
  13. -- 缓冲区最大下标
  14. local INDEX_MAX = 256
  15. -- 是否有socket正处在链接
  16. local socketsConnected = 0
  17. --- SOCKET 是否有可用
  18. -- @return 可用true,不可用false
  19. -- socket4G.isReady = link.isReady
  20. local function errorInd(error)
  21. local coSuspended = {}
  22. for _, c in pairs(sockets) do -- IP状态出错时,通知所有已连接的socket
  23. c.error = error
  24. --不能打开如下3行代码,IP出错时,会通知每个socket,socket会主动close
  25. --如果设置了connected=false,则主动close时,直接退出,不会执行close动作,导致core中的socket资源没释放
  26. --会引发core中socket耗尽以及socket id重复的问题
  27. --c.connected = false
  28. --socketsConnected = c.connected or socketsConnected
  29. --if error == 'CLOSED' then sys.publish("SOCKET_ACTIVE", socketsConnected) end
  30. if c.co and coroutine.status(c.co) == "suspended" then
  31. --coroutine.resume(c.co, false)
  32. table.insert(coSuspended, c.co)
  33. end
  34. end
  35. for k, v in pairs(coSuspended) do
  36. if v and coroutine.status(v) == "suspended" then
  37. coroutine.resume(v, false, error)
  38. end
  39. end
  40. end
  41. sys.subscribe("IP_ERROR_IND", function()errorInd('IP_ERROR_IND') end)
  42. --sys.subscribe('IP_SHUT_IND', function()errorInd('CLOSED') end)
  43. -- 创建socket函数
  44. local mt = {}
  45. mt.__index = mt
  46. local function socket(protocol, cert, tCoreExtPara)
  47. local ssl = protocol:match("SSL")
  48. local co = coroutine.running()
  49. if not co then
  50. log.warn("socket.socket: socket must be called in coroutine")
  51. return nil
  52. end
  53. -- 实例的属性参数表
  54. local o = {
  55. id = nil,
  56. protocol = protocol,
  57. tCoreExtPara = tCoreExtPara,
  58. ssl = ssl,
  59. cert = cert,
  60. co = co,
  61. input = {},
  62. output = {},
  63. wait = "",
  64. connected = false,
  65. iSubscribe = false,
  66. subMessage = nil,
  67. isBlock = false,
  68. msg = nil,
  69. rcvProcFnc = nil,
  70. }
  71. return setmetatable(o, mt)
  72. end
  73. --- 创建基于TCP的socket对象
  74. -- @bool[opt=nil] ssl,是否为ssl连接,true表示是,其余表示否
  75. -- @table[opt=nil] cert,ssl连接需要的证书配置,只有ssl参数为true时,此参数才有意义,cert格式如下:
  76. -- {
  77. -- caCert = "ca.crt", --CA证书文件(Base64编码 X.509格式),如果存在此参数,则表示客户端会对服务器的证书进行校验;不存在则不校验
  78. -- clientCert = "client.crt", --客户端证书文件(Base64编码 X.509格式),服务器对客户端的证书进行校验时会用到此参数
  79. -- clientKey = "client.key", --客户端私钥文件(Base64编码 X.509格式)
  80. -- clientPassword = "123456", --客户端证书文件密码[可选]
  81. -- insist = 1, --证书中的域名校验失败时,是否坚持连接,默认为1,坚持连接,0为不连接
  82. -- }
  83. -- @number[opt=nil] tCoreExtPara, 建立链接扩展参数
  84. -- {
  85. -- rcvBufferSize = "num" --接收缓冲区大小,默认为0
  86. -- }
  87. -- @return client,创建成功返回socket客户端对象;创建失败返回nil
  88. -- @usage
  89. -- c = socket.tcp()
  90. -- c = socket.tcp(true)
  91. -- c = socket.tcp(true, {caCert="ca.crt"})
  92. -- c = socket.tcp(true, {caCert="ca.crt", clientCert="client.crt", clientKey="client.key"})
  93. -- c = socket.tcp(true, {caCert="ca.crt", clientCert="client.crt", clientKey="client.key", clientPassword="123456"})
  94. function tcp(ssl, cert, tCoreExtPara)
  95. return socket("TCP" .. (ssl == true and "SSL" or ""), (ssl == true) and cert or nil, tCoreExtPara)
  96. end
  97. --- 创建基于UDP的socket对象
  98. -- @return client,创建成功返回socket客户端对象;创建失败返回nil
  99. -- @usage c = socket.udp()
  100. function udp()
  101. return socket("UDP")
  102. end
  103. --- 连接服务器
  104. -- @string address 服务器地址,支持ip和域名
  105. -- @param port string或者number类型,服务器端口
  106. -- @number[opt=120] timeout 可选参数,连接超时时间,单位秒
  107. -- @return bool result true - 成功,false - 失败
  108. -- @return string ,id '0' -- '8' ,返回通道ID编号
  109. -- @usage
  110. -- socketClient = socket.tcp()
  111. -- socketClient:connect("www.baidu.com","80")
  112. function mt:connect(address, port, timeout)
  113. assert(self.co == coroutine.running(), "socket:connect: coroutine mismatch")
  114. if not link.isReady() then
  115. log.info("socket.connect: ip not ready")
  116. return false
  117. end
  118. self.address = address
  119. self.port = port
  120. local tCoreExtPara = self.tCoreExtPara or {}
  121. -- 默认缓冲区大小
  122. local rcvBufferSize = tCoreExtPara.rcvBufferSize or 0
  123. local socket_connect_fnc = (type(socketcore.sock_conn_ext)=="function") and socketcore.sock_conn_ext or socketcore.sock_conn
  124. if self.protocol == 'TCP' then
  125. self.id = socket_connect_fnc(0, address, port, rcvBufferSize)
  126. elseif self.protocol == 'TCPSSL' then
  127. local cert = {hostName = address}
  128. local insist = 1
  129. if self.cert then
  130. if self.cert.caCert then
  131. if self.cert.caCert:sub(1, 1) ~= "/" then self.cert.caCert = "/lua/" .. self.cert.caCert end
  132. cert.caCert = io.readFile(self.cert.caCert)
  133. end
  134. if self.cert.clientCert then
  135. if self.cert.clientCert:sub(1, 1) ~= "/" then self.cert.clientCert = "/lua/" .. self.cert.clientCert end
  136. cert.clientCert = io.readFile(self.cert.clientCert)
  137. end
  138. if self.cert.clientKey then
  139. if self.cert.clientKey:sub(1, 1) ~= "/" then self.cert.clientKey = "/lua/" .. self.cert.clientKey end
  140. cert.clientKey = io.readFile(self.cert.clientKey)
  141. end
  142. insist = self.cert.insist == 0 and 0 or 1
  143. end
  144. self.id = socket_connect_fnc(2, address, port, cert, rcvBufferSize, insist)
  145. else
  146. self.id = socket_connect_fnc(1, address, port, rcvBufferSize)
  147. end
  148. if type(socketcore.sock_conn_ext)=="function" then
  149. if not self.id or self.id<0 then
  150. if self.id==-2 then
  151. require "http"
  152. --请求腾讯云免费HttpDns解析
  153. http.request("GET", "119.29.29.29/d?dn=" .. address, nil, nil, nil, 40000,
  154. function(result, statusCode, head, body)
  155. log.info("socket.httpDnsCb", result, statusCode, head, body)
  156. sys.publish("SOCKET_HTTPDNS_RESULT_"..address.."_"..port, result, statusCode, head, body)
  157. end)
  158. local _, result, statusCode, head, body = sys.waitUntil("SOCKET_HTTPDNS_RESULT_"..address.."_"..port)
  159. --DNS解析成功
  160. if result and statusCode == "200" and body and body:match("^[%d%.]+") then
  161. return self:connect(body:match("^([%d%.]+)"),port,timeout)
  162. end
  163. end
  164. self.id = nil
  165. end
  166. end
  167. if not self.id then
  168. log.info("socket:connect: core sock conn error", self.protocol, address, port, self.cert)
  169. return false
  170. end
  171. log.info("socket:connect-coreid,prot,addr,port,cert,timeout", self.id, self.protocol, address, port, self.cert, timeout or 60)
  172. sockets[self.id] = self
  173. self.wait = "SOCKET_CONNECT"
  174. self.timerId = sys.timerStart(coroutine.resume, (timeout or 120) * 1000, self.co, false, "TIMEOUT")
  175. local result, reason = coroutine.yield()
  176. if self.timerId and reason ~= "TIMEOUT" then sys.timerStop(self.timerId) end
  177. if not result then
  178. log.info("socket:connect: connect fail", reason)
  179. if reason == "RESPONSE" then
  180. sockets[self.id] = nil
  181. self.id = nil
  182. end
  183. sys.publish("LIB_SOCKET_CONNECT_FAIL_IND", self.ssl, self.protocol, address, port)
  184. return false
  185. end
  186. log.info("socket:connect: connect ok")
  187. if not self.connected then
  188. self.connected = true
  189. socketsConnected = socketsConnected+1
  190. sys.publish("SOCKET_ACTIVE", socketsConnected>0)
  191. end
  192. return true, self.id
  193. end
  194. --- 异步发送数据
  195. -- @number[opt=nil] keepAlive,服务器和客户端最大通信间隔时间,也叫心跳包最大时间,单位秒
  196. -- @string[opt=nil] pingreq,心跳包的字符串
  197. -- @return boole,false 失败,true 表示成功
  198. -- @usage
  199. -- socketClient = socket.tcp()
  200. -- socketClient:connect("www.baidu.com","80")
  201. -- while socketClient:asyncSelect() do end
  202. function mt:asyncSelect(keepAlive, pingreq)
  203. assert(self.co == coroutine.running(), "socket:asyncSelect: coroutine mismatch")
  204. if self.error then
  205. log.warn('socket.client:asyncSelect', 'error', self.error)
  206. return false
  207. end
  208. self.wait = "SOCKET_SEND"
  209. local dataLen = 0
  210. --log.info("socket.asyncSelect #self.output",#self.output)
  211. while #self.output ~= 0 do
  212. local data = table.concat(self.output)
  213. dataLen = string.len(data)
  214. self.output = {}
  215. local sendSize = self.protocol == "UDP" and 1472 or SENDSIZE
  216. for i = 1, dataLen, sendSize do
  217. -- 按最大MTU单元对data分包
  218. socketcore.sock_send(self.id, data:sub(i, i + sendSize - 1))
  219. if self.timeout then
  220. self.timerId = sys.timerStart(coroutine.resume, self.timeout * 1000, self.co, false, "TIMEOUT")
  221. end
  222. --log.info("socket.asyncSelect self.timeout",self.timeout)
  223. local result, reason = coroutine.yield()
  224. if self.timerId and reason ~= "TIMEOUT" then sys.timerStop(self.timerId) end
  225. sys.publish("SOCKET_ASYNC_SEND", result)
  226. if not result then
  227. sys.publish("LIB_SOCKET_SEND_FAIL_IND", self.ssl, self.protocol, self.address, self.port)
  228. --log.warn('socket.asyncSelect', 'send error')
  229. return false
  230. end
  231. end
  232. end
  233. self.wait = "SOCKET_WAIT"
  234. --log.info("socket.asyncSelect",dataLen,self.id)
  235. if dataLen>0 then sys.publish("SOCKET_SEND", self.id, true) end
  236. if keepAlive and keepAlive ~= 0 then
  237. if type(pingreq) == "function" then
  238. sys.timerStart(pingreq, keepAlive * 1000)
  239. else
  240. sys.timerStart(self.asyncSend, keepAlive * 1000, self, pingreq or "\0")
  241. end
  242. end
  243. return coroutine.yield()
  244. end
  245. function mt:getAsyncSend()
  246. if self.error then return 0 end
  247. return #(self.output)
  248. end
  249. --- 异步缓存待发送的数据
  250. -- @string data 数据
  251. -- @number[opt=nil] timeout 可选参数,发送超时时间,单位秒;为nil时表示不支持timeout
  252. -- @return result true - 成功,false - 失败
  253. -- @usage
  254. -- socketClient = socket.tcp()
  255. -- socketClient:connect("www.baidu.com","80")
  256. -- socketClient:asyncSend("12345678")
  257. function mt:asyncSend(data, timeout)
  258. if self.error then
  259. log.warn('socket.client:asyncSend', 'error', self.error)
  260. return false
  261. end
  262. self.timeout = timeout
  263. table.insert(self.output, data or "")
  264. --log.info("socket.asyncSend",self.wait)
  265. if self.wait == "SOCKET_WAIT" then coroutine.resume(self.co, true) end
  266. return true
  267. end
  268. --- 异步接收数据
  269. -- @return data 表示接收到的数据(如果是UDP,返回最新的一包数据;如果是TCP,返回所有收到的数据)
  270. -- ""表示未收到数据
  271. -- @usage
  272. -- socketClient = socket.tcp()
  273. -- socketClient:connect("www.baidu.com","80")
  274. -- data = socketClient:asyncRecv()
  275. function mt:asyncRecv()
  276. if #self.input == 0 then return "" end
  277. if self.protocol == "UDP" then
  278. return table.remove(self.input)
  279. else
  280. local s = table.concat(self.input)
  281. self.input = {}
  282. if self.isBlock then table.insert(self.input, socketcore.sock_recv(self.msg.socket_index, self.msg.recv_len)) end
  283. return s
  284. end
  285. end
  286. --- 同步发送数据
  287. -- @string data 数据
  288. -- 此处传入的数据长度和剩余可用内存有关,只要内存够用,可以随便传入数据
  289. -- 虽然说此处的数据长度没有特别限制,但是调用core中的socket发送接口时,每次最多发送11200字节的数据
  290. -- 例如此处传入的data长度是112000字节,则在这个send接口中,会循环10次,每次发送11200字节的数据
  291. -- @number[opt=120] timeout 可选参数,发送超时时间,单位秒
  292. -- @return result true - 成功,false - 失败
  293. -- @usage
  294. -- socketClient = socket.tcp()
  295. -- socketClient:connect("www.baidu.com","80")
  296. -- socketClient:send("12345678")
  297. function mt:send(data, timeout)
  298. assert(self.co == coroutine.running(), "socket:send: coroutine mismatch")
  299. if self.error then
  300. log.warn('socket.client:send', 'error', self.error)
  301. return false
  302. end
  303. log.debug("socket.send", "total " .. string.len(data or "") .. " bytes", "first 30 bytes", (data or ""):sub(1, 30))
  304. local sendSize = self.protocol == "UDP" and 1472 or SENDSIZE
  305. for i = 1, string.len(data or ""), sendSize do
  306. -- 按最大MTU单元对data分包
  307. self.wait = "SOCKET_SEND"
  308. socketcore.sock_send(self.id, data:sub(i, i + sendSize - 1))
  309. self.timerId = sys.timerStart(coroutine.resume, (timeout or 120) * 1000, self.co, false, "TIMEOUT")
  310. local result, reason = coroutine.yield()
  311. if self.timerId and reason ~= "TIMEOUT" then sys.timerStop(self.timerId) end
  312. if not result then
  313. log.info("socket:send", "send fail", reason)
  314. sys.publish("LIB_SOCKET_SEND_FAIL_IND", self.ssl, self.protocol, self.address, self.port)
  315. return false
  316. end
  317. end
  318. return true
  319. end
  320. --- 同步接收数据
  321. -- @number[opt=0] timeout 可选参数,接收超时时间,单位毫秒
  322. -- @string[opt=nil] msg 可选参数,控制socket所在的线程退出recv阻塞状态
  323. -- @bool[opt=nil] msgNoResume 可选参数,控制socket所在的线程退出recv阻塞状态
  324. -- false或者nil表示“在recv阻塞状态,收到msg消息,可以退出阻塞状态”,true表示不退出
  325. -- 此参数仅lib内部使用,应用脚本不要使用此参数
  326. -- @return result 数据接收结果
  327. -- true表示成功(接收到了数据)
  328. -- false表示失败(没有接收到数据)
  329. -- @return data
  330. -- 如果result为true,data表示接收到的数据(如果是UDP,返回最新的一包数据;如果是TCP,返回所有收到的数据)
  331. -- 如果result为false,超时失败,data为"timeout"
  332. -- 如果result为false,msg控制退出,data为msg的字符串
  333. -- 如果result为false,socket连接被动断开控制退出,data为"CLOSED"
  334. -- 如果result为false,PDP断开连接控制退出,data为"IP_ERROR_IND"
  335. -- @return param 如果是msg控制退出,param的值是msg的参数
  336. -- @usage
  337. -- socketClient = socket.tcp()
  338. -- socketClient:connect("www.baidu.com","80")
  339. -- result,data = socketClient:recv(60000,"APP_SOCKET_SEND_DATA")
  340. function mt:recv(timeout, msg, msgNoResume)
  341. assert(self.co == coroutine.running(), "socket:recv: coroutine mismatch")
  342. if self.error then
  343. log.warn('socket.client:recv', 'error', self.error)
  344. return false
  345. end
  346. self.msgNoResume = msgNoResume
  347. if msg and not self.iSubscribe then
  348. self.iSubscribe = msg
  349. self.subMessage = function(data)
  350. --if data then table.insert(self.output, data) end
  351. if self.wait == "+RECEIVE" and not self.msgNoResume then
  352. if data then table.insert(self.output, data) end
  353. coroutine.resume(self.co, 0xAA)
  354. end
  355. end
  356. sys.subscribe(msg, self.subMessage)
  357. end
  358. if msg and #self.output > 0 then sys.publish(msg, false) end
  359. if #self.input == 0 then
  360. self.wait = "+RECEIVE"
  361. if timeout and timeout > 0 then
  362. local r, s = sys.wait(timeout)
  363. if r == nil then
  364. return false, "timeout"
  365. elseif r == 0xAA then
  366. local dat = table.concat(self.output)
  367. self.output = {}
  368. return false, msg, dat
  369. else
  370. return r, s
  371. end
  372. else
  373. local r, s = coroutine.yield()
  374. if r == 0xAA then
  375. local dat = table.concat(self.output)
  376. self.output = {}
  377. return false, msg, dat
  378. else
  379. return r, s
  380. end
  381. end
  382. end
  383. if self.protocol == "UDP" then
  384. local s = table.remove(self.input)
  385. return true, s
  386. else
  387. log.warn("-------------------使用缓冲区---------------")
  388. local s = table.concat(self.input)
  389. self.input = {}
  390. if self.isBlock then table.insert(self.input, socketcore.sock_recv(self.msg.socket_index, self.msg.recv_len)) end
  391. return true, s
  392. end
  393. end
  394. --- 主动关闭并且销毁一个socket
  395. -- @return nil
  396. -- @usage
  397. -- socketClient = socket.tcp()
  398. -- socketClient:connect("www.baidu.com","80")
  399. -- socketClient:close()
  400. function mt:close()
  401. assert(self.co == coroutine.running(), "socket:close: coroutine mismatch")
  402. if self.iSubscribe then
  403. sys.unsubscribe(self.iSubscribe, self.subMessage)
  404. self.iSubscribe = false
  405. end
  406. --此处不要再判断状态,否则在连接超时失败时,conneted状态仍然是未连接,会导致无法close
  407. --if self.connected then
  408. log.info("socket:sock_close", self.id)
  409. local result, reason
  410. if self.id then
  411. socketcore.sock_close(self.id)
  412. self.wait = "SOCKET_CLOSE"
  413. while true do
  414. result, reason = coroutine.yield()
  415. if reason == "RESPONSE" then break end
  416. end
  417. end
  418. if self.connected then
  419. self.connected = false
  420. if socketsConnected>0 then
  421. socketsConnected = socketsConnected-1
  422. end
  423. sys.publish("SOCKET_ACTIVE", socketsConnected>0)
  424. end
  425. if self.input then
  426. self.input = {}
  427. end
  428. --end
  429. if self.id ~= nil then
  430. sockets[self.id] = nil
  431. end
  432. end
  433. -- socket接收自定义控制处理
  434. -- @function[opt=nil] rcvCbFnc,socket接收到数据后,执行的回调函数,回调函数的调用形式为:
  435. -- rcvCbFnc(readFnc,socketIndex,rcvDataLen)
  436. -- rcvCbFnc内部,会判断是否读取数据,如果读取,执行readFnc(socketIndex,rcvDataLen),返回true;否则返回false或者nil
  437. function mt:setRcvProc(rcvCbFnc)
  438. assert(self.co == coroutine.running(), "socket:setRcvProc: coroutine mismatch")
  439. self.rcvProcFnc = rcvCbFnc
  440. end
  441. local function on_response(msg)
  442. local t = {
  443. [rtos.MSG_SOCK_CLOSE_CNF] = 'SOCKET_CLOSE',
  444. [rtos.MSG_SOCK_SEND_CNF] = 'SOCKET_SEND',
  445. [rtos.MSG_SOCK_CONN_CNF] = 'SOCKET_CONNECT',
  446. }
  447. if not sockets[msg.socket_index] then
  448. log.warn('response on nil socket', msg.socket_index, t[msg.id], msg.result)
  449. return
  450. end
  451. if sockets[msg.socket_index].wait ~= t[msg.id] then
  452. log.warn('response on invalid wait', sockets[msg.socket_index].id, sockets[msg.socket_index].wait, t[msg.id], msg.socket_index)
  453. return
  454. end
  455. log.info("socket:on_response:", msg.socket_index, t[msg.id], msg.result)
  456. if type(socketcore.sock_destroy) == "function" then
  457. if (msg.id == rtos.MSG_SOCK_CONN_CNF and msg.result ~= 0) or msg.id == rtos.MSG_SOCK_CLOSE_CNF then
  458. socketcore.sock_destroy(msg.socket_index)
  459. end
  460. end
  461. coroutine.resume(sockets[msg.socket_index].co, msg.result == 0, "RESPONSE")
  462. end
  463. rtos.on(rtos.MSG_SOCK_CLOSE_CNF, on_response)
  464. rtos.on(rtos.MSG_SOCK_CONN_CNF, on_response)
  465. rtos.on(rtos.MSG_SOCK_SEND_CNF, on_response)
  466. rtos.on(rtos.MSG_SOCK_CLOSE_IND, function(msg)
  467. log.info("socket.rtos.MSG_SOCK_CLOSE_IND")
  468. if not sockets[msg.socket_index] then
  469. log.warn('close ind on nil socket', msg.socket_index, msg.id)
  470. return
  471. end
  472. if sockets[msg.socket_index].connected then
  473. sockets[msg.socket_index].connected = false
  474. if socketsConnected>0 then
  475. socketsConnected = socketsConnected-1
  476. end
  477. sys.publish("SOCKET_ACTIVE", socketsConnected>0)
  478. end
  479. sockets[msg.socket_index].error = 'CLOSED'
  480. --[[
  481. if type(socketcore.sock_destroy) == "function" then
  482. socketcore.sock_destroy(msg.socket_index)
  483. end]]
  484. sys.publish("LIB_SOCKET_CLOSE_IND", sockets[msg.socket_index].ssl, sockets[msg.socket_index].protocol, sockets[msg.socket_index].address, sockets[msg.socket_index].port)
  485. coroutine.resume(sockets[msg.socket_index].co, false, "CLOSED")
  486. end)
  487. rtos.on(rtos.MSG_SOCK_RECV_IND, function(msg)
  488. if not sockets[msg.socket_index] then
  489. log.warn('close ind on nil socket', msg.socket_index, msg.id)
  490. return
  491. end
  492. -- local s = socketcore.sock_recv(msg.socket_index, msg.recv_len)
  493. -- log.debug("socket.recv", "total " .. msg.recv_len .. " bytes", "first " .. 30 .. " bytes", s:sub(1, 30))
  494. log.debug("socket.recv", msg.recv_len, sockets[msg.socket_index].rcvProcFnc)
  495. if sockets[msg.socket_index].rcvProcFnc then
  496. sockets[msg.socket_index].rcvProcFnc(socketcore.sock_recv, msg.socket_index, msg.recv_len)
  497. else
  498. if sockets[msg.socket_index].wait == "+RECEIVE" then
  499. coroutine.resume(sockets[msg.socket_index].co, true, socketcore.sock_recv(msg.socket_index, msg.recv_len))
  500. else -- 数据进缓冲区,缓冲区溢出采用覆盖模式
  501. if #sockets[msg.socket_index].input > INDEX_MAX then
  502. log.error("socket recv", "out of stack", "block")
  503. -- sockets[msg.socket_index].input = {}
  504. sockets[msg.socket_index].isBlock = true
  505. sockets[msg.socket_index].msg = msg
  506. else
  507. sockets[msg.socket_index].isBlock = false
  508. table.insert(sockets[msg.socket_index].input, socketcore.sock_recv(msg.socket_index, msg.recv_len))
  509. end
  510. sys.publish("SOCKET_RECV", msg.socket_index)
  511. end
  512. end
  513. end)
  514. --- 设置TCP层自动重传的参数
  515. -- @number[opt=4] retryCnt,重传次数;取值范围0到12
  516. -- @number[opt=16] retryMaxTimeout,限制每次重传允许的最大超时时间(单位秒),取值范围1到16
  517. -- @return nil
  518. -- @usage
  519. -- setTcpResendPara(3,8)
  520. -- setTcpResendPara(4,16)
  521. function setTcpResendPara(retryCnt, retryMaxTimeout)
  522. ril.request("AT+TCPUSERPARAM=6," .. (retryCnt or 4) .. ",7200," .. (retryMaxTimeout or 16))
  523. end
  524. --- 设置域名解析参数
  525. -- 注意:0027以及之后的core版本才支持此功能
  526. -- @number[opt=4] retryCnt,重传次数;取值范围1到8
  527. -- @number[opt=4] retryTimeoutMulti,重传超时时间倍数,取值范围1到5
  528. -- 第n次重传超时时间的计算方式为:第n次的重传超时基数*retryTimeoutMulti,单位为秒
  529. -- 重传超时基数表为{1, 1, 2, 4, 4, 4, 4, 4}
  530. -- 第1次重传超时时间为:1*retryTimeoutMulti 秒
  531. -- 第2次重传超时时间为:1*retryTimeoutMulti 秒
  532. -- 第3次重传超时时间为:2*retryTimeoutMulti 秒
  533. -- ...........................................
  534. -- 第8次重传超时时间为:8*retryTimeoutMulti 秒
  535. -- @return nil
  536. -- @usage
  537. -- socket.setDnsParsePara(8,5)
  538. function setDnsParsePara(retryCnt, retryTimeoutMulti)
  539. ril.request("AT*DNSTMOUT="..(retryCnt or 4)..","..(retryTimeoutMulti or 4))
  540. end
  541. --- 打印所有socket的状态
  542. -- @return 无
  543. -- @usage socket.printStatus()
  544. function printStatus()
  545. for _, client in pairs(sockets) do
  546. for k, v in pairs(client) do
  547. log.info('socket.printStatus', 'client', client.id, k, v)
  548. end
  549. end
  550. end
  551. --- 设置数据传输后,允许进入休眠状态的延时时长
  552. -- 3024版本以及之后的版本才支持此功能
  553. -- 此功能设置的参数,设置成功后,掉电会自动保存
  554. -- @number tm,数据传输后,允许进入休眠状态的延时时长,单位为秒,取值范围1到20
  555. -- 注意:此时间越短,允许进入休眠状态越快,功耗越低;但是在某些网络环境中,此时间越短,可能会造成数据传输不稳定
  556. -- 建议在可以接受的功耗范围内,此值设置的越大越好
  557. -- 如果没有设置此参数,此延时时长是和基站的配置有关,一般来说是10秒左右
  558. -- @return nil
  559. -- @usage
  560. -- socket.setLowPower(5)
  561. function setLowPower(tm)
  562. ril.request("AT*RTIME="..tm)
  563. end
  564. --setDnsParsePara(4,4)
  565. --setTcpResendPara(1,16)