main.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. local skynet = require "skynet"
  2. local httpc = require "http.httpc"
  3. local httpurl = require "http.url"
  4. local dns = require "skynet.dns"
  5. local runconfig = require "run_config"
  6. local socket = require "skynet.socket"
  7. local httpd = require "http.httpd"
  8. local sockethelper = require "http.sockethelper"
  9. local cjson = require "cjson"
  10. local skynet_manager = require "skynet.manager"
  11. local function http_test(protocol)
  12. --httpc.dns() -- set dns server
  13. httpc.timeout = 100 -- set timeout 1 second
  14. print("GET baidu.com")
  15. protocol = protocol or "http"
  16. local respheader = {}
  17. local host = string.format("%s://baidu.com", protocol)
  18. print("geting... ".. host)
  19. local status, body = httpc.get(host, "/", respheader)
  20. print("[header] =====>")
  21. for k,v in pairs(respheader) do
  22. print(k,v)
  23. end
  24. print("[body] =====>", status)
  25. print(body)
  26. local respheader = {}
  27. local ip = dns.resolve "baidu.com"
  28. print(string.format("GET %s (baidu.com)", ip))
  29. local status, body = httpc.get(host, "/", respheader, { host = "baidu.com" })
  30. print(status)
  31. end
  32. local function response(id, ...)
  33. local ok, err = httpd.write_response(sockethelper.writefunc(id), ...)
  34. if not ok then
  35. -- if err == sockethelper.socket_error , that means socket closed.
  36. skynet.error(string.format("fd = %d, %s", id, err))
  37. end
  38. end
  39. function json_test()
  40. local myTable = {name = "John", age = 30, city = "New York"}
  41. local jsonStr = cjson.encode(myTable)
  42. print(jsonStr)
  43. jsonStr = '{"name":"John","age":30,"city":"New York"}'
  44. local decodedTable = cjson.decode(jsonStr)
  45. print(decodedTable.name)
  46. print(decodedTable.age)
  47. print(decodedTable.city)
  48. end
  49. skynet.start(function()
  50. skynet.uniqueservice("dbproxy", "book_server")
  51. skynet.uniqueservice("agent_manager", "agent_manager")
  52. local back_srv = skynet.newservice("backmgr", "backmgr", 0)
  53. skynet.name("backmgr", back_srv)
  54. --接收消息的服务
  55. local httpworks = {}
  56. local protocol = "http"
  57. for i= 1, 30 do --开启30个服务用来接收消息
  58. httpworks[i] = skynet.newservice("http_work", "http_work", protocol)
  59. end
  60. local http_balance = 1
  61. local id = socket.listen("0.0.0.0",runconfig.httpProt )
  62. socket.start(id , function(id, addr)
  63. skynet.send(httpworks[http_balance], "lua", id,addr)
  64. http_balance = http_balance + 1
  65. if http_balance > #httpworks then
  66. http_balance = 1
  67. end
  68. end)
  69. end)