Skynet基础教程02.service基础操作

2017-03-26  本文已影响0人  JasminePowered

本篇主要内容

需要前提了解的知识

lua service基础操作

创建与销毁

projects/hello_world中,我们在配置文件指定了主入口服务,类似main函数,一般会通过它来启动其他的service。接下来我们来分析下它的代码:

local Skynet = require "skynet"
local Log = require "log"

local function __init__()
    Skynet.newservice('debug_console', Skynet.getenv("CONSOLE_PORT"))
    Skynet.newservice('hello_world')
    Skynet.exit()
end

Skynet.start(__init__)
print("my_addr:", Skynet.self()) -- 获取自己地址
local obj = Skynet.newservice("hello_world") -- 创建并把地址记录下来
Skynet.kill(obj) -- 杀掉目标

消息发送与分发

Skynet.send(addr, "lua", "test_send", "hello jasmine")
Skynet.call(addr, "lua", "test_call", 1, 2)
local CMD = {}
function CMD.test_send(s)
    print("test_send:", s)
end

function CMD.test_call(a, b)
    print("test_call:", a, b)
    Skynet.retpack({code = 200, sum = a + b})
end

Skynet.dispatch("lua", function(session, source, cmd, ...)
    local f = assert(CMD[cmd])
    f(...)
end)
-- 发送者和接收者都需要注册
skynet.register_protocol {
  name = "text", # 协议名称
  id = skynet.PTYPE_TEXT, # 协议ID
  pack = function(m) return tostring(m) end, # 消息编码
  unpack = skynet.tostring, # 消息解码
}

需要注意的地方

练习题

参考资料

官方Wiki LuaApi
练习题仓库

上一篇 下一篇

猜你喜欢

热点阅读