PageRenderTime 40ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lualib/socket.lua

https://github.com/evoup/skynet
Lua | 80 lines | 67 code | 13 blank | 0 comment | 8 complexity | 12bc1a46b45f477c76b5127477145cf0 MD5 | raw file
  1. local skynet = require "skynet"
  2. local c = require "socket.c"
  3. local socket = {}
  4. local fd
  5. local object
  6. local data = {}
  7. local function presend()
  8. if next(data) then
  9. local tmp = data
  10. data = {}
  11. for _,v in ipairs(tmp) do
  12. socket.write(fd, v)
  13. end
  14. end
  15. end
  16. function socket.connect(addr)
  17. local ip, port = string.match(addr,"([^:]+):(.+)")
  18. port = tonumber(port)
  19. socket.close()
  20. fd = c.open(ip,port)
  21. if fd == nil then
  22. return true
  23. end
  24. skynet.send(".connection", "text", "ADD", fd , skynet.address(skynet.self()))
  25. object = c.new()
  26. presend()
  27. end
  28. function socket.stdin()
  29. skynet.send(".connection", "text", "ADD", 1 , skynet.address(skynet.self()))
  30. object = c.new()
  31. end
  32. function socket.push(msg,sz)
  33. if msg then
  34. c.push(object, msg, sz)
  35. end
  36. end
  37. function socket.read(bytes)
  38. return c.read(object, bytes)
  39. end
  40. function socket.readline(sep)
  41. return c.readline(object, sep)
  42. end
  43. function socket.readblock(...)
  44. return c.readblock(object,...)
  45. end
  46. function socket.write(...)
  47. local str = c.write(fd, ...)
  48. if str then
  49. socket.close()
  50. table.insert(data, str)
  51. end
  52. end
  53. function socket.writeblock(...)
  54. local str = c.writeblock(fd, ...)
  55. if str then
  56. socket.close()
  57. table.insert(data, str)
  58. end
  59. end
  60. function socket.close()
  61. if fd then
  62. c.close(fd)
  63. skynet.send(".connection","text", "DEL", fd)
  64. fd = nil
  65. end
  66. end
  67. return socket