北京市住房及城乡建设部网站,房源网站建设,计算机应用技术移动互联网开发,网站引导页动态效果怎么做写在前面
skynet 服务之间有自己的一套高效通信 API 。本文给出简单的示例。 文章目录 写在前面准备工作编写代码运行结果 准备工作
首先要有一个编译好#xff0c;而且工作正常的 skynet 。
编写代码
在 skynet/example 目录编写一个配置文件#xff0c;两个代码文件。 …写在前面
skynet 服务之间有自己的一套高效通信 API 。本文给出简单的示例。 文章目录 写在前面准备工作编写代码运行结果 准备工作
首先要有一个编译好而且工作正常的 skynet 。
编写代码
在 skynet/example 目录编写一个配置文件两个代码文件。
calc.lua 提供数值计算服务。
local skynet require skynetlocal CALC {}-- 处理加法
function CALC.add(...)local res 0for i, v in ipairs{...} dores res vendreturn res
end-- 处理减法
function CALC.sub(lhs, rhs)local res lhs - rhsskynet.error(lhs .. - .. rhs .. .. res)
end-- 处理 lua 消息
function lua_dispatch(session, source, cmd, ...)local f assert(CALC[cmd])skynet.ret(skynet.pack(f(...)))
endskynet.start(function()-- 注册 lua 消息的处理函数skynet.dispatch(lua, lua_dispatch)
end)主服务 main_test 负责启动 calc 之后周期发出数值计算请求。
local skynet require skynet
require skynet.manager-- 初始化函数
function init()math.randomseed(math.floor(skynet.time()))-- 启动一个服务并命名local calc_serv skynet.newservice(calc)skynet.name(.calc, calc_serv)
end-- 服务函数
function task_add()while true do-- 加法local a math.random(1, 100)local b math.random(1, 100)local c math.random(1, 100)local ret skynet.call(.calc, lua, add, a, b, c)skynet.error(a .. .. b .. .. c .. .. ret)-- 睡眠一秒skynet.sleep(300)end
endfunction task_sub()while true do-- 减法local lhs math.random(1, 100)local rhs math.random(1, 100)local ret skynet.send(.calc, lua, sub, lhs, rhs)-- 睡眠 1500msskynet.sleep(150)end
end-- 注册初始化函数
skynet.init(init)-- 启动服务
skynet.start(function()skynet.fork(task_add)skynet.fork(task_sub)
end)配置文件 config_test
-- 启动多少个工作线程
thread 8-- skynet 工作在单节点模式下
harbor 0-- skynet 节点的主程序
start main_test-- lua 服务代码所在的位置
luaservice ./service/?.lua;./examples/?.lua运行结果
rootmacbook:~/skynet# ./skynet examples/config_test
[:00000001] LAUNCH logger
[:00000002] LAUNCH snlua bootstrap
[:00000003] LAUNCH snlua launcher
[:00000004] LAUNCH snlua cdummy
[:00000005] LAUNCH harbor 0 4
[:00000006] LAUNCH snlua datacenterd
[:00000007] LAUNCH snlua service_mgr
[:00000008] LAUNCH snlua main_test
[:00000009] LAUNCH snlua calc
[:00000008] 52 77 75 204
[:00000008] 25 - 56 -31
...