share.lua 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. local skynet = require "skynet"
  2. local sharedata = require "skynet.sharedata"
  3. local mode = ...
  4. if mode == "host" then
  5. skynet.start(function()
  6. skynet.error("new foobar")
  7. sharedata.new("foobar", { a=1, b= { "hello", "world" } })
  8. skynet.fork(function()
  9. skynet.sleep(200) -- sleep 2s
  10. skynet.error("update foobar a = 2")
  11. sharedata.update("foobar", { a =2 })
  12. skynet.sleep(200) -- sleep 2s
  13. skynet.error("update foobar a = 3")
  14. sharedata.update("foobar", { a = 3, b = { "change" } })
  15. skynet.sleep(100)
  16. skynet.error("delete foobar")
  17. sharedata.delete "foobar"
  18. end)
  19. end)
  20. else
  21. skynet.start(function()
  22. skynet.newservice(SERVICE_NAME, "host")
  23. local obj = sharedata.query "foobar"
  24. local b = obj.b
  25. skynet.error(string.format("a=%d", obj.a))
  26. for k,v in ipairs(b) do
  27. skynet.error(string.format("b[%d]=%s", k,v))
  28. end
  29. -- test lua serialization
  30. local s = skynet.packstring(obj)
  31. local nobj = skynet.unpack(s)
  32. for k,v in pairs(nobj) do
  33. skynet.error(string.format("nobj[%s]=%s", k,v))
  34. end
  35. for k,v in ipairs(nobj.b) do
  36. skynet.error(string.format("nobj.b[%d]=%s", k,v))
  37. end
  38. for i = 1, 5 do
  39. skynet.sleep(100)
  40. skynet.error("second " ..i)
  41. for k,v in pairs(obj) do
  42. skynet.error(string.format("%s = %s", k , tostring(v)))
  43. end
  44. end
  45. local ok, err = pcall(function()
  46. local tmp = { b[1], b[2] } -- b is invalid , so pcall should failed
  47. end)
  48. if not ok then
  49. skynet.error(err)
  50. end
  51. -- obj. b is not the same with local b
  52. for k,v in ipairs(obj.b) do
  53. skynet.error(string.format("b[%d] = %s", k , tostring(v)))
  54. end
  55. collectgarbage()
  56. skynet.error("sleep")
  57. skynet.sleep(100)
  58. b = nil
  59. collectgarbage()
  60. skynet.error("sleep")
  61. skynet.sleep(100)
  62. skynet.exit()
  63. end)
  64. end