概述
skynet是云风开源的C实现的游戏服务器框架,架构上高性能,代码上干净整洁,提供lua接口灵活开发业务逻辑。skynet提供了socket、message、timer、http等基本能力,除此之外不做任何高维功能。
架构概览
skynet.c
main
static void
start(int thread) {
pthread_t pid[thread+3];
struct monitor *m = skynet_malloc(sizeof(*m));
memset(m, 0, sizeof(*m));
m->count = thread;
m->sleep = 0;
m->m = skynet_malloc(thread * sizeof(struct skynet_monitor *));
int i;
for (i=0;i<thread;i++) {
m->m[i] = skynet_monitor_new();
}
if (pthread_mutex_init(&m->mutex, NULL)) {
fprintf(stderr, "Init mutex error");
exit(1);
}
if (pthread_cond_init(&m->cond, NULL)) {
fprintf(stderr, "Init cond error");
exit(1);
}
create_thread(&pid[0], thread_monitor, m);
create_thread(&pid[1], thread_timer, m);
create_thread(&pid[2], thread_socket, m);
static int weight[] = {
-1, -1, -1, -1, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, };
struct worker_parm wp[thread];
for (i=0;i<thread;i++) {
wp[i].m = m;
wp[i].id = i;
if (i < sizeof(weight)/sizeof(weight[0])) {
wp[i].weight= weight[i];
} else {
wp[i].weight = 0;
}
create_thread(&pid[i+3], thread_worker, &wp[i]);
}
for (i=0;i<thread+3;i++) {
pthread_join(pid[i], NULL);
}
free_monitor(m);
}
socket
socket模块是对网络,主要是epoll相关的封装,核心的函数有
thread_socket
skynet_socket_poll
socket_server_poll
forward_message
skynet_context_push
mq
mq模块支持了skynet消息驱动+回调函数的处理模式,核心函数有:
thread_worker
skynet_mq_push
skynet_mq_pop
skynet_context_message_dispatch
dispatch_message
timer
timer模块是对0.01s精度的计时器实现,使用多level结构,类似于linux的简单实现;
thread_timer
skynet_updatetime
timer_update
systime
monitor
monitor模块非常简单,监控消息的处理异常
skynet.lua
参考lua_c_example,skynet也是类似的:
- C编写核心代码
- C编写lua的core api
- lua编写调用的C的user api
- 用户使用lua编程,不需要1行C语言
实战
example
./skynet examples/config # Launch first skynet node (Gate server) and a skynet-master (see config for standalone option)
./3rd/lua/lua examples/client.lua # Launch a client, and try to input hello.
others
参考资料
timer