当前位置:首页 >> 智能终端演进 >> 【skynet】skynet 服务间通信,高仿手机网

【skynet】skynet 服务间通信,高仿手机网

cpugpu芯片开发光刻机 智能终端演进 1
文件名:【skynet】skynet 服务间通信,高仿手机网 【skynet】skynet 服务间通信 写在前面

skynet 服务之间有自己的一套高效通信 API 。本文给出简单的示例。

文章目录 写在前面准备工作编写代码运行结果


准备工作

首先要有一个编译好,而且工作正常的 skynet 。

编写代码

在 skynet/example 目录编写一个配置文件,两个代码文件。

calc.lua 提供数值计算服务。

local skynet = require "skynet"local CALC = {}-- 处理加法function CALC.add(...)local res = 0for i, v in ipairs{...} dores = res + vendreturn resend-- 处理减法function CALC.sub(lhs, rhs)return lhs - rhsend-- 处理 lua 消息function lua_handle(session, source, cmd, ...)local f = assert(CALC[cmd])skynet.ret(skynet.pack(f(...)))endfunction task()-- 注册 lua 消息的处理函数skynet.dispatch("lua", lua_handle)endskynet.start(task)

主服务 main_test 负责启动 calc ,之后周期发出数值计算请求。

local skynet = require "skynet"local calc_serv = nil-- 初始化函数function init()math.randomseed(math.floor(skynet.time()))calc_serv = skynet.newservice("calc")end-- 服务函数function task()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_serv, "lua", "add", a, b, c)skynet.error(a .. " + " .. b .. " + " .. c .. " = " .. ret)-- 睡眠三秒skynet.sleep(300)-- 减法local lhs = math.random(1, 100)local rhs = math.random(1, 100)local ret = skynet.call(calc_serv, "lua", "sub", lhs, rhs)skynet.error(lhs .. " - " .. rhs .. " = " .. ret)-- 睡眠三秒skynet.sleep(300)endend-- 注册初始化函数skynet.init(init)-- 启动服务skynet.start(task)

配置文件 config_test

-- 启动多少个工作线程thread = 8-- skynet 工作在单节点模式下harbor = 0-- skynet 节点的主程序start = "main_test"-- lua 服务代码所在的位置luaservice = "./service/?.lua;./examples/?.lua" 运行结果 root@macbook:~/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...
协助本站SEO优化一下,谢谢!
关键词不能为空
同类推荐
«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接