├── .cproject ├── .gitignore ├── .project ├── Makefile ├── ReadMe.md ├── config ├── node │ ├── daemon_conf.xml │ └── node_conf.xml ├── sql │ ├── game.sql │ └── log.sql ├── struct │ ├── client_msg.xml │ ├── client_struct.xml │ ├── http_msg.xml │ ├── node_msg.xml │ ├── node_struct.xml │ └── websocket_msg.xml └── xml │ └── general.xml ├── daemon ├── Daemon_Server.cpp ├── Daemon_Server.h ├── Makefile └── main.cpp ├── daemon_server ├── doc ├── nodelib.tar.gz ├── uglifyjs.sh ├── v8.tar.gz ├── websocket.html ├── 强制删除文件.bat ├── 服务器UML类图.vsd ├── 服务器导出API.xlsx ├── 服务器性能测试.docx ├── 服务器技术说明.docx ├── 服务器架构图.ppt └── 服务器问题及解决方案.docx ├── js ├── center_server │ └── center_server.js ├── config.js ├── data_server │ └── data_server.js ├── enum.js ├── game_server │ ├── activity.js │ ├── bag.js │ ├── entity.js │ ├── game_player.js │ ├── game_server.js │ ├── login.js │ └── mail.js ├── gate_server │ ├── gate_server.js │ └── session.js ├── global.js ├── log_server │ └── log_server.js ├── master_server │ └── master_server.js ├── message.js ├── public_server │ ├── guild.js │ ├── public_player.js │ ├── public_server.js │ └── rank.js ├── struct.js ├── timer.js └── util.js ├── kill.sh ├── main.cpp ├── make_plugin.sh ├── node_server.vcxproj ├── node_server.vcxproj.user ├── nodelib ├── Makefile ├── base │ ├── Aes.cpp │ ├── Aes.h │ ├── Base_Define.cpp │ ├── Base_Define.h │ ├── Base_Enum.h │ ├── Base_Function.cpp │ ├── Base_Function.h │ ├── Bit_Buffer.h │ ├── Buffer_List.h │ ├── Buffer_Pool_Group.h │ ├── Byte_Buffer.h │ ├── Compress.cpp │ ├── Compress.h │ ├── Config.cpp │ ├── Config.h │ ├── Date_Time.cpp │ ├── Date_Time.h │ ├── List.h │ ├── Log.cpp │ ├── Log.h │ ├── Object_Pool.h │ ├── Priority_Queue.h │ ├── Proc_Info.cpp │ ├── Proc_Info.h │ ├── Sha1.cpp │ ├── Sha1.h │ ├── Thread.h │ ├── Thread_Guard.h │ ├── Thread_Lock.h │ ├── Time_Value.cpp │ └── Time_Value.h ├── db │ ├── DB_Operator.h │ ├── Data_Manager.cpp │ ├── Data_Manager.h │ ├── Mongo_Operator.cpp │ ├── Mongo_Operator.h │ ├── Mysql_Conn.cpp │ ├── Mysql_Conn.h │ ├── Mysql_Operator.cpp │ └── Mysql_Operator.h ├── network │ ├── Accept.cpp │ ├── Accept.h │ ├── Connect.cpp │ ├── Connect.h │ ├── Endpoint.cpp │ ├── Endpoint.h │ ├── Epoll_Watcher.cpp │ ├── Epoll_Watcher.h │ ├── Event_Handler.h │ ├── Http_Client.cpp │ ├── Http_Client.h │ ├── Http_Parser_Wrap.cpp │ ├── Http_Parser_Wrap.h │ ├── Network.cpp │ ├── Network.h │ ├── Svc.cpp │ ├── Svc.h │ ├── Svc_Http.cpp │ ├── Svc_Http.h │ ├── Svc_Static_List.h │ ├── Svc_Tcp.cpp │ ├── Svc_Tcp.h │ ├── Svc_WebSocket.cpp │ ├── Svc_WebSocket.h │ ├── http_parser.cpp │ └── http_parser.h ├── node │ ├── Hot_Update.cpp │ ├── Hot_Update.h │ ├── Node_Define.cpp │ ├── Node_Define.h │ ├── Node_Endpoint.cpp │ ├── Node_Endpoint.h │ ├── Node_Manager.cpp │ ├── Node_Manager.h │ ├── Node_Timer.cpp │ └── Node_Timer.h ├── struct │ ├── Base_Struct.cpp │ ├── Base_Struct.h │ ├── DB_Struct.cpp │ ├── DB_Struct.h │ ├── Msg_Struct.cpp │ ├── Msg_Struct.h │ ├── Robot_Struct.cpp │ ├── Robot_Struct.h │ ├── Struct_Manager.cpp │ ├── Struct_Manager.h │ ├── Struct_Tool.cpp │ └── Struct_Tool.h ├── v8 │ ├── V8_Base.cpp │ ├── V8_Base.h │ ├── V8_Manager.cpp │ ├── V8_Manager.h │ ├── V8_Wrap.cpp │ └── V8_Wrap.h └── xml │ ├── Xml.cpp │ ├── Xml.h │ ├── tinystr.cpp │ ├── tinystr.h │ ├── tinyxml.cpp │ ├── tinyxml.h │ ├── tinyxmlerror.cpp │ └── tinyxmlparser.cpp ├── plugin ├── aoi │ ├── Aoi_Entity.cpp │ ├── Aoi_Entity.h │ ├── Aoi_Manager.cpp │ ├── Aoi_Manager.h │ ├── Aoi_Wrap.cpp │ ├── Aoi_Wrap.h │ ├── Makefile │ └── main.cpp ├── db │ ├── DB_Manager.cpp │ ├── DB_Manager.h │ ├── Makefile │ └── main.cpp ├── gate │ ├── Gate_Manager.cpp │ ├── Gate_Manager.h │ ├── Gate_Wrap.cpp │ ├── Gate_Wrap.h │ ├── Makefile │ └── main.cpp ├── log │ ├── Log_Manager.cpp │ ├── Log_Manager.h │ ├── Makefile │ └── main.cpp └── monitor │ ├── Makefile │ ├── Monitor_Manager.cpp │ ├── Monitor_Manager.h │ └── main.cpp └── start.sh /.gitignore: -------------------------------------------------------------------------------- 1 | /Debug/ 2 | /Release/ 3 | /.obj/ 4 | /log/ 5 | /natives_blob.bin 6 | /snapshot_blob.bin 7 | /node_server 8 | /plugin/*.so 9 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | node_server 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.cdt.managedbuilder.core.genmakebuilder 10 | clean,full,incremental, 11 | 12 | 13 | 14 | 15 | org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder 16 | full,incremental, 17 | 18 | 19 | 20 | 21 | 22 | org.eclipse.cdt.core.cnature 23 | org.eclipse.cdt.core.ccnature 24 | org.eclipse.cdt.managedbuilder.core.managedBuildNature 25 | org.eclipse.cdt.managedbuilder.core.ScannerConfigNature 26 | 27 | 28 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ############################################################################## 2 | # # 3 | # 默认为release模式编译,debug模式请使用参数'MODE=DEBUG' # 4 | # # 5 | ############################################################################## 6 | 7 | ###在这里添加源文件目录### 8 | SRCDIR= ./\ 9 | 10 | ###这里定义目标文件目录### 11 | OBJDIR =./.obj/ 12 | 13 | TARGET_NAME=node_server 14 | 15 | BIN=./ 16 | 17 | INCLUDE=-I/usr/local/include/nodelib/base\ 18 | -I/usr/local/include/nodelib/network\ 19 | -I/usr/local/include/nodelib/node\ 20 | -I/usr/local/include/nodelib/v8\ 21 | -I/usr/local/include/nodelib/xml\ 22 | $(addprefix -I, $(SRCDIR)) 23 | 24 | LIBDIR=-L./ 25 | 26 | LIB=-lnodelib\ 27 | 28 | CC=g++ 29 | 30 | DEPENDS=-MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" 31 | 32 | ifeq ($(MODE), DEBUG) 33 | BUILD_FLAG = -O0 -g3 34 | else 35 | BUILD_FLAG = -O3 36 | endif 37 | 38 | CONDITION= 39 | 40 | COM_FLAG=-Wall -c -fmessage-length=0 -std=c++11 41 | 42 | LDFLAG= 43 | 44 | BIN_TARGET=$(OBJDIR)bin/$(TARGET_NAME) 45 | 46 | SRCS=$(wildcard $(addsuffix *.cpp, $(SRCDIR))) 47 | 48 | OBJECTS:=$(addprefix $(OBJDIR), $(subst ./,,$(SRCS:.cpp=.o))) 49 | 50 | .PHONY:all mkobjdir clean dep 51 | 52 | all:mkobjdir $(BIN_TARGET) 53 | 54 | -include $(OBJECTS:.o=.d) 55 | 56 | $(BIN_TARGET):$(OBJECTS) 57 | @echo "Linking target $@" 58 | $(CC) $(LDFLAG) -o $@ $^ $(LIBDIR) $(LIB) 59 | @echo " " 60 | @echo "Finished building target: $(TARGET_NAME)" 61 | @echo " " 62 | @-cp -f $(BIN_TARGET) $(BIN) 63 | @-sh make_plugin.sh 64 | 65 | $(OBJDIR)%.o:%.cpp 66 | ifeq ($(MODE), DEBUG) 67 | @echo "Building DEBUG MODE target $@" 68 | else 69 | @echo "Building RELEASE MODE target $@" 70 | endif 71 | $(CC) $(INCLUDE) $(BUILD_FLAG) $(COM_FLAG) $(DEPENDS) $(CONDITION) -o "$(@)" "$(<)" 72 | @echo " " 73 | 74 | mkobjdir: 75 | @test -d $(OBJDIR) || (mkdir $(OBJDIR) && mkdir $(OBJDIR)bin $(addprefix $(OBJDIR), $(subst ./,,$(SRCDIR)))) 76 | 77 | dep: 78 | @tar -zvx -f doc/nodelib.tar.gz -C doc 79 | @mv doc/nodelib/libnodelib.so /usr/local/lib64/ 80 | @cp -rf doc/nodelib/* /usr/local/include/nodelib 81 | @rm -rf doc/nodelib/ 82 | @echo "install nodelib file success" 83 | @tar -zvx -f doc/v8.tar.gz -C doc 84 | @cp -rf doc/v8/include/* /usr/local/include/include 85 | @cp -rf doc/v8/*.so /usr/local/lib64 86 | @cp -rf doc/v8/*.bin ./ 87 | @rm -rf doc/v8/ 88 | @ldconfig 89 | 90 | clean: 91 | -rm -rf $(OBJDIR) 92 | -------------------------------------------------------------------------------- /ReadMe.md: -------------------------------------------------------------------------------- 1 | 服务器是异步非阻塞的多进程多线程架构,运行于CentOS7操作系统。服务器底层使用C++编写,高效稳定, 2 | 使用TCP协议进行进程间以及与客户端的通信。同时也支持UDP、Websocket、Http协议。 3 | 网络通信协议使用自定义格式,具备加密功能,安全高效。游戏数据库支持MongoDB和Mysql,可以选择自己想要的数据库。 4 | 逻辑层使用简单高效的Javascript进行开发,集成Google V8引擎解析脚本,保证脚本运行效率,有js经验的开发人员可以快速上手。 5 | 6 | 服务器分为DaemonServer,MasterServer,CenterServer,GateServer,GameServer,PublicServer,ChatServer,DBServer,LogServer。 7 | 8 | DaemonServer:守护服务器,管理本机所有服务器进程的重启,通过进程id控制。 9 | MasterServer:管理服务器,管理进程的启动关闭,记录进程的状态,然后将进程状态转给DaemonServer管理,可以动态增加进程。 10 | CenterServer:中心服务器,管理gate列表,选择gate,验证客户端token,管理gate和game进程动态增减。 11 | GateServer:网关服务器,维持客户端连接,消息转发,选择game功能。 12 | GameServer:游戏服务器,处理玩家游戏逻辑,场景,AOI等功能。 13 | PublicServer:公共服务器,处理公会,排行榜,拍卖行等公共游戏逻辑。 14 | ChatServer:聊天服务器,处理聊天,开房间,发红包等功能。 15 | DBServer:数据库服务器,提供在线玩家数据缓存和公共数据缓存,提交数据存取接口。 16 | LogServer:日志服务器,游戏日志存储功能。 17 | 18 | -------------------------------------------------------------------------------- /config/node/daemon_conf.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /config/sql/game.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE IF NOT EXISTS `game` DEFAULT CHARACTER SET utf8; 2 | USE game 3 | 4 | DROP TABLE IF EXISTS `rank`; 5 | CREATE TABLE `rank` ( 6 | rank_type bigint(20) NOT NULL default '0', 7 | min_role_id bigint(20) NOT NULL default '0', 8 | min_value int(11) NOT NULL default '0', 9 | member_map text NOT NULL, 10 | PRIMARY KEY (rank_type) 11 | )ENGINE=InnoDB DEFAULT CHARSET=utf8; 12 | 13 | DROP TABLE IF EXISTS `mail`; 14 | CREATE TABLE `mail` ( 15 | role_id bigint(20) NOT NULL default '0', 16 | total_count int(11) NOT NULL default '0', 17 | mail_map text NOT NULL, 18 | PRIMARY KEY (role_id) 19 | )ENGINE=InnoDB DEFAULT CHARSET=utf8; 20 | 21 | DROP TABLE IF EXISTS `bag`; 22 | CREATE TABLE `bag` ( 23 | role_id bigint(20) NOT NULL default '0', 24 | item_map text NOT NULL, 25 | PRIMARY KEY (role_id) 26 | )ENGINE=InnoDB DEFAULT CHARSET=utf8; 27 | 28 | DROP TABLE IF EXISTS `activity`; 29 | CREATE TABLE `activity` ( 30 | role_id bigint(20) NOT NULL default '0', 31 | seven_day_start_time int(11) NOT NULL default '0', 32 | seven_day_award_status text NOT NULL, 33 | sign_in_award_status text NOT NULL, 34 | PRIMARY KEY (role_id) 35 | )ENGINE=InnoDB DEFAULT CHARSET=utf8; 36 | 37 | DROP TABLE IF EXISTS `role`; 38 | CREATE TABLE `role` ( 39 | role_id bigint(20) NOT NULL default '0', 40 | role_name varchar(120) NOT NULL default '', 41 | account varchar(120) NOT NULL default '', 42 | gender int(11) NOT NULL default '0', 43 | career int(11) NOT NULL default '0', 44 | level int(11) NOT NULL default '0', 45 | exp int(11) NOT NULL default '0', 46 | combat int(11) NOT NULL default '0', 47 | create_time int(11) NOT NULL default '0', 48 | login_time int(11) NOT NULL default '0', 49 | logout_time int(11) NOT NULL default '0', 50 | gold int(11) NOT NULL default '0', 51 | diamond int(11) NOT NULL default '0', 52 | guild_id bigint(20) NOT NULL default '0', 53 | guild_name varchar(120) NOT NULL default '', 54 | speed int(11) NOT NULL default '0', 55 | last_scene int(11) NOT NULL default '0', 56 | last_x int(11) NOT NULL default '0', 57 | last_y int(11) NOT NULL default '0', 58 | PRIMARY KEY (role_id) 59 | )ENGINE=InnoDB DEFAULT CHARSET=utf8; 60 | 61 | DROP TABLE IF EXISTS `account`; 62 | CREATE TABLE `account` ( 63 | account varchar(120) NOT NULL default '', 64 | role_list text NOT NULL, 65 | PRIMARY KEY (account) 66 | )ENGINE=InnoDB DEFAULT CHARSET=utf8; 67 | 68 | DROP TABLE IF EXISTS `idx`; 69 | CREATE TABLE `idx` ( 70 | type varchar(120) NOT NULL default '', 71 | value int(11) NOT NULL default '0', 72 | PRIMARY KEY (type) 73 | )ENGINE=InnoDB DEFAULT CHARSET=utf8; 74 | 75 | DROP TABLE IF EXISTS `guild`; 76 | CREATE TABLE `guild` ( 77 | guild_id bigint(20) NOT NULL default '0', 78 | guild_name varchar(120) NOT NULL default '', 79 | chief_id bigint(20) NOT NULL default '0', 80 | create_time int(11) NOT NULL default '0', 81 | member_list text NOT NULL, 82 | PRIMARY KEY (guild_id) 83 | )ENGINE=InnoDB DEFAULT CHARSET=utf8; 84 | -------------------------------------------------------------------------------- /config/sql/log.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE IF NOT EXISTS `log` DEFAULT CHARACTER SET utf8; 2 | USE log 3 | 4 | DROP TABLE IF EXISTS `logout`; 5 | CREATE TABLE `logout` ( 6 | role_id bigint(20) NOT NULL default '0', 7 | role_name varchar(120) NOT NULL default '', 8 | account varchar(120) NOT NULL default '', 9 | gender int(11) NOT NULL default '0', 10 | career int(11) NOT NULL default '0', 11 | level int(11) NOT NULL default '0', 12 | exp int(11) NOT NULL default '0', 13 | create_time int(11) NOT NULL default '0', 14 | login_time int(11) NOT NULL default '0', 15 | logout_time int(11) NOT NULL default '0', 16 | PRIMARY KEY (role_id) 17 | )ENGINE=InnoDB DEFAULT CHARSET=utf8; 18 | -------------------------------------------------------------------------------- /config/struct/client_struct.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /config/struct/http_msg.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /config/struct/websocket_msg.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /config/xml/general.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /daemon/Daemon_Server.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Daemon_Server.h 3 | * 4 | * Created on: Oct 29, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef DAEMON_H_ 9 | #define DAEMON_H_ 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | struct Node_Info { 17 | int node_type; //节点类型 18 | int node_id; //节点id 19 | int endpoint_gid; //端点组id 20 | std::string node_name; //节点名称 21 | }; 22 | 23 | class Daemon_Server { 24 | typedef std::vector Node_List; 25 | //pid--Node_Info 26 | typedef std::unordered_map Pid_Node_Map; 27 | //node_id--core_num 28 | typedef std::unordered_map Node_Core_Map; 29 | public: 30 | static Daemon_Server *instance(void); 31 | 32 | int init(int argc, char *argv[]); 33 | int start(int argc, char *argv[]); 34 | 35 | void run_daemon_server(void); 36 | int fork_process(int node_type, int node_id, int endpoint_gid, std::string &node_name); 37 | static void sigcld_handle(int signo); 38 | void restart_process(int pid); 39 | 40 | private: 41 | Daemon_Server(void); 42 | ~Daemon_Server(void); 43 | Daemon_Server(const Daemon_Server &); 44 | const Daemon_Server &operator=(const Daemon_Server &); 45 | 46 | private: 47 | static Daemon_Server *instance_; 48 | 49 | std::string exec_name_; 50 | std::string label_; 51 | 52 | Node_List node_list_; 53 | Pid_Node_Map pid_node_map_; 54 | Node_Core_Map node_core_map_; 55 | }; 56 | 57 | #define DAEMON_SERVER Daemon_Server::instance() 58 | 59 | #endif /* DAEMON_H_ */ 60 | -------------------------------------------------------------------------------- /daemon/Makefile: -------------------------------------------------------------------------------- 1 | ############################################################################## 2 | # # 3 | # 默认为release模式编译,debug模式请使用参数'MODE=DEBUG' # 4 | # # 5 | ############################################################################## 6 | 7 | ###在这里添加源文件目录### 8 | SRCDIR= ./\ 9 | 10 | ###这里定义目标文件目录### 11 | OBJDIR =./.obj/ 12 | 13 | TARGET_NAME=daemon_server 14 | 15 | BIN=./ 16 | 17 | INCLUDE=-I/usr/local/include/nodelib/base\ 18 | -I/usr/local/include/nodelib/struct\ 19 | -I/usr/local/include/nodelib/xml\ 20 | $(addprefix -I, $(SRCDIR)) 21 | 22 | LIBDIR=-L./ 23 | 24 | LIB=-lnodelib\ 25 | 26 | CC=g++ 27 | 28 | DEPENDS=-MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" 29 | 30 | ifeq ($(MODE), DEBUG) 31 | BUILD_FLAG = -O0 -g3 32 | else 33 | BUILD_FLAG = -O3 34 | endif 35 | 36 | CONDITION= 37 | 38 | COM_FLAG=-Wall -c -fmessage-length=0 -std=c++11 39 | 40 | LDFLAG= 41 | 42 | BIN_TARGET=$(OBJDIR)bin/$(TARGET_NAME) 43 | 44 | SRCS=$(wildcard $(addsuffix *.cpp, $(SRCDIR))) 45 | 46 | OBJECTS:=$(addprefix $(OBJDIR), $(subst ./,,$(SRCS:.cpp=.o))) 47 | 48 | .PHONY:all mkobjdir clean config 49 | 50 | all:mkobjdir $(BIN_TARGET) 51 | 52 | -include $(OBJECTS:.o=.d) 53 | 54 | $(BIN_TARGET):$(OBJECTS) 55 | @echo "Linking target $@" 56 | $(CC) $(LDFLAG) -o $@ $^ $(LIBDIR) $(LIB) 57 | @echo " " 58 | @echo "Finished building target: $(TARGET_NAME)" 59 | @echo " " 60 | @-cp -f $(BIN_TARGET) $(BIN) 61 | 62 | $(OBJDIR)%.o:%.cpp 63 | ifeq ($(MODE), DEBUG) 64 | @echo "Building DEBUG MODE target $@" 65 | else 66 | @echo "Building RELEASE MODE target $@" 67 | endif 68 | $(CC) $(INCLUDE) $(BUILD_FLAG) $(COM_FLAG) $(DEPENDS) $(CONDITION) -o "$(@)" "$(<)" 69 | @echo " " 70 | 71 | mkobjdir: 72 | @test -d $(OBJDIR) || (mkdir $(OBJDIR) && mkdir $(OBJDIR)bin $(addprefix $(OBJDIR), $(subst ./,,$(SRCDIR)))) 73 | 74 | clean: 75 | -rm -rf $(OBJDIR) -------------------------------------------------------------------------------- /daemon/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * main.cpp 3 | * Created on: Oct 29, 2016 4 | * Author: zhangyalei 5 | */ 6 | 7 | #include 8 | #include 9 | #include "Aes.h" 10 | #include "Compress.h" 11 | #include "Struct_Tool.h" 12 | #include "Daemon_Server.h" 13 | 14 | struct option long_options[] = { 15 | {"struct_tool", no_argument, 0, 's'}, 16 | {"compress", no_argument, 0, 'c'}, 17 | {"decompress", no_argument, 0, 'd'}, 18 | {0, 0, 0, 0} 19 | }; 20 | 21 | int parse_cmd_arguments(int argc, char *argv[]) { 22 | Struct_Tool tool; 23 | bool daemon = true; 24 | int c = 0; 25 | while ((c = getopt_long_only(argc, argv, "vdm:", long_options, NULL)) != -1) { 26 | //带参数时候,不启动daemon_server 27 | daemon = false; 28 | switch (c) { 29 | case 's': { //struct_tool 30 | tool.write_struct(); 31 | break; 32 | } 33 | case 'c': { //compress 34 | folder_encrypt("js/"); 35 | folder_comp("js/"); 36 | break; 37 | } 38 | case 'd': { //decompress 39 | folder_decomp("js/"); 40 | folder_decrypt("js/"); 41 | break; 42 | } 43 | default: { 44 | break; 45 | } 46 | } 47 | } 48 | 49 | if (daemon) { 50 | tool.write_struct(); 51 | DAEMON_SERVER->init(argc, argv); 52 | DAEMON_SERVER->start(argc, argv); 53 | } 54 | return 0; 55 | } 56 | 57 | static void sighandler(int sig_no) { exit(0); } /// for gprof need normal exit 58 | 59 | int main(int argc, char *argv[]) { 60 | signal(SIGPIPE, SIG_IGN); 61 | signal(SIGUSR1, sighandler); 62 | 63 | parse_cmd_arguments(argc, argv); 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /daemon_server: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/daemon_server -------------------------------------------------------------------------------- /doc/nodelib.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/doc/nodelib.tar.gz -------------------------------------------------------------------------------- /doc/uglifyjs.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | function read_dir() { 3 | for file in `ls $1` 4 | do 5 | if [ -d $1"/"$file ] 6 | then 7 | read_dir $1"/"$file 8 | else 9 | echo "uglify" $1"/"$file 10 | ../../UglifyJS2/bin/uglifyjs $1"/"$file -c -m -o $1"/"$file 11 | fi 12 | done 13 | } 14 | 15 | echo "********uglify js begin********" 16 | read_dir ../js 17 | echo "********uglify js end**********" 18 | -------------------------------------------------------------------------------- /doc/v8.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/doc/v8.tar.gz -------------------------------------------------------------------------------- /doc/websocket.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | websocket test 7 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /doc/强制删除文件.bat: -------------------------------------------------------------------------------- 1 | DEL /F /A /Q \\?\%1 2 | RD /S /Q \\?\%1 -------------------------------------------------------------------------------- /doc/服务器UML类图.vsd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/doc/服务器UML类图.vsd -------------------------------------------------------------------------------- /doc/服务器导出API.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/doc/服务器导出API.xlsx -------------------------------------------------------------------------------- /doc/服务器性能测试.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/doc/服务器性能测试.docx -------------------------------------------------------------------------------- /doc/服务器技术说明.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/doc/服务器技术说明.docx -------------------------------------------------------------------------------- /doc/服务器架构图.ppt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/doc/服务器架构图.ppt -------------------------------------------------------------------------------- /doc/服务器问题及解决方案.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/doc/服务器问题及解决方案.docx -------------------------------------------------------------------------------- /js/config.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 描述:配置文件 3 | * 作者:张亚磊 4 | * 时间:2016/03/24 5 | */ 6 | 7 | function Config() { 8 | this.general = null; 9 | 10 | this.init = function() { 11 | try { 12 | this.general = read_xml("config/xml/general.xml"); 13 | } catch (err) { 14 | log_error(err.message); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /js/data_server/data_server.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 描述:data_server脚本 3 | * 作者:张亚磊 4 | * 时间:2016/09/22 5 | */ 6 | 7 | function init(node_info) { 8 | log_info('data_server init, node_type:', node_info.node_type, ' node_id:', node_info.node_id, ' node_name:', node_info.node_name); 9 | global.node_info = node_info; 10 | global.timer.init(); 11 | 12 | for(var i = 0; i < node_info.endpoint_list.length; ++i) { 13 | if (node_info.endpoint_list[i].endpoint_type == Endpoint_Type.CONNECTOR) { 14 | util.sync_node_info(node_info.endpoint_list[i].endpoint_id); 15 | } 16 | } 17 | } 18 | 19 | function on_hotupdate(file_path) { } 20 | 21 | function on_drop_eid(eid) { 22 | util.sync_node_info(eid); 23 | } 24 | 25 | function on_drop_cid(cid) { } 26 | 27 | function on_msg(msg) { } 28 | 29 | function on_tick(timer_id) { 30 | var timer_handler = global.timer.get_timer_handler(timer_id); 31 | if (timer_handler != null) { 32 | timer_handler(); 33 | } 34 | } -------------------------------------------------------------------------------- /js/game_server/bag.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 描述:背包系统 3 | * 作者:张亚磊 4 | * 时间:2016/02/26 5 | */ 6 | 7 | function Bag() { 8 | this.game_player = null; 9 | this.bag_info = null; 10 | } 11 | 12 | Bag.prototype.load_data = function(game_player, player_data) { 13 | this.game_player = game_player; 14 | this.bag_info = player_data.bag_info; 15 | } 16 | 17 | Bag.prototype.save_data = function(player_data) { 18 | player_data.bag_info = this.bag_info; 19 | } 20 | 21 | Bag.prototype.insert_item = function(item_info) { 22 | var item_list = new Array(); 23 | item_list.push(item_info); 24 | return this.insert_item_list(item_list); 25 | } 26 | 27 | Bag.prototype.insert_item_list = function(item_list) { 28 | if (this.bag_info.item_map.size + item_list.length > 1000) { 29 | return this.game_player.send_error_msg(Error_Code.BAG_FULL); 30 | } 31 | for (var i = 0; i < item_list.length; ++i) { 32 | var item_info = this.bag_info.item_map.get(item_list[i].item_id); 33 | if (item_info == null) { 34 | this.bag_info.item_map.set(item_list[i].item_id, item_list[i]); 35 | } else { 36 | item_info.amount += item_list[i].amount; 37 | } 38 | } 39 | 40 | this.active_item_info(); 41 | return 0; 42 | } 43 | 44 | Bag.prototype.erase_item = function(item_info) { 45 | var item_list = new Array(); 46 | item_list.push(item_info); 47 | return this.erase_item_list(item_list); 48 | } 49 | 50 | Bag.prototype.erase_item_list = function(item_list) { 51 | for (var i = 0; i < item_list.length; ++i) { 52 | var item_info = this.bag_info.item_map.get(item_list[i].id); 53 | if (item_info == null) { 54 | return this.game_player.send_error_msg(Error_Code.ITEM_NOT_EXIST); 55 | } else { 56 | if (item_info.amount < item_list[i].amount) { 57 | return this.game_player.send_error_msg(Error_Code.ITEM_NOT_ENOUGH); 58 | } 59 | } 60 | } 61 | 62 | for (var i = 0; i < item_list.length; ++i) { 63 | var item_info = this.bag_info.item_map.get(item_list[i].id); 64 | item_info.amount -= item_list[i].amount; 65 | if (item_info.amount == 0) { 66 | this.bag_info.item_map.delete(item.id); 67 | } 68 | } 69 | 70 | this.active_item_info(); 71 | return 0; 72 | } 73 | 74 | Bag.prototype.active_item_info = function() { 75 | } -------------------------------------------------------------------------------- /js/game_server/mail.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 描述:邮件系统 3 | * 作者:张亚磊 4 | * 时间:2016/02/24 5 | */ 6 | 7 | function Mail() { 8 | this.game_player = null; 9 | this.mail_info = null; 10 | } 11 | 12 | Mail.prototype.load_data = function(game_player, player_data) { 13 | this.game_player = game_player; 14 | this.mail_info = player_data.mail_info; 15 | } 16 | 17 | Mail.prototype.save_data = function(player_data) { 18 | player_data.mail_info = this.mail_info; 19 | } 20 | 21 | Mail.prototype.fetch_mail_info = function() { 22 | var msg_res = new Object(); 23 | msg_res.mail_list = new Array(); 24 | this.mail_info.mail_map.forEach(function(value, key, map) { 25 | msg_res.mail_list.push(value); 26 | }); 27 | this.game_player.send_msg(Msg.RES_MAIL_INFO, msg_res); 28 | } 29 | 30 | Mail.prototype.pickup_mail = function(msg) { 31 | var msg_res = new Object(); 32 | msg_res.mail_id_list = new Array(); 33 | if (msg.mail_id == 0) { 34 | this.mail_info.mail_map.forEach(function(value, key, map) { 35 | var result = this.pickup_item_money(value); 36 | if (result == 0) { 37 | msg_res.mail_id_list.push(key); 38 | } 39 | }); 40 | } else { 41 | var mail_detail = this.mail_info.mail_map.get(msg.mail_id); 42 | if (mail_detail == null) { 43 | return this.game_player.send_error_msg(Error_Code.CLIENT_PARAM_ERROR); 44 | } 45 | 46 | var result = this.pickup_item_money(value); 47 | if (result == 0) { 48 | msg_res.mail_id_list.push(msg.mail_id); 49 | } 50 | } 51 | this.game_player.send_msg(Msg.RES_PICKUP_MAIL, msg_res); 52 | } 53 | 54 | Mail.prototype.delete_mail = function(msg) { 55 | var msg_res = new Object(); 56 | msg_res.mail_id_list = new Array(); 57 | if (msg.mail_id == 0) { 58 | this.mail_info.mail_map.forEach(function(value, key, map) { 59 | var result = this.pickup_item_money(value); 60 | if (result == 0) { 61 | msg_res.mail_id_list.push(key); 62 | } 63 | }); 64 | this.mail_info.mail_map.clear(); 65 | } else { 66 | var mail_detail = this.mail_info.mail_map.get(msg.mail_id); 67 | if (mail_detail == null) { 68 | return this.game_player.send_error_msg(Error_Code.CLIENT_PARAM_ERROR); 69 | } 70 | 71 | var result = this.pickup_item_money(value); 72 | if (result == 0) { 73 | msg_res.mail_id_list.push(msg.mail_id); 74 | this.mail_info.mail_map.delete(msg.mail_id); 75 | } 76 | } 77 | this.game_player.send_msg(Msg.RES_DEL_MAIL, msg_res); 78 | } 79 | 80 | Mail.prototype.receive_mail = function(mail_detail) { 81 | this.mail_info.total_count++; 82 | mail_detail.mail_id = 1000000 + total_count; 83 | this.mail_info.mail_map.set(mail_detail.mail_id, mail_detail); 84 | } 85 | 86 | Mail.prototype.pickup_item_money = function(mail_detail) { 87 | var result = this.game_player.bag.insert_item_list(mail_detail.item_list); 88 | if (result != 0) { 89 | return result; 90 | } 91 | 92 | result = this.game_player.add_money(mail_detail.gold, mail_detail.diamond); 93 | if (result != 0) { 94 | return result; 95 | } 96 | 97 | mail_detail.pickup = true; 98 | this.game_player.data_change = true; 99 | return 0; 100 | } 101 | -------------------------------------------------------------------------------- /js/gate_server/session.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 描述:session类 3 | * 作者:张亚磊 4 | * 时间:2016/02/24 5 | */ 6 | 7 | function Session() { 8 | this.client_eid = 0; //gate向client发消息的端点id 9 | this.client_cid = 0; //client与gate连接的cid 10 | this.game_eid = 0; //gate向game发消息的端点id 11 | this.game_cid = 0; //game与gate连接的cid 12 | this.sid = 0; //gate生成的全局唯一session_id 13 | this.account = ""; //client帐号名 14 | this.last_hb_time = 0;//上次心跳时间 15 | this.latency = 0; //上次心跳到本次心跳经过的时间 16 | } 17 | 18 | Session.prototype.on_heartbeat = function (msg) { 19 | this.last_hb_time = util.now_sec(); 20 | this.latency = this.last_hb_time - msg.client_time; 21 | if (this.latency < 0) this.latency = 0; 22 | 23 | var msg_res = new Object(); 24 | msg_res.server_time = this.last_hb_time; 25 | send_msg(Endpoint.GATE_CLIENT_SERVER, msg.cid, Msg.RES_HEARTBEAT, Msg_Type.TCP_S2C, 0, msg_res); 26 | } 27 | -------------------------------------------------------------------------------- /js/global.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/js/global.js -------------------------------------------------------------------------------- /js/log_server/log_server.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 描述:log_server脚本 3 | * 作者:张亚磊 4 | * 时间:2016/09/22 5 | */ 6 | 7 | function init(node_info) { 8 | log_info('log_server init, node_type:', node_info.node_type, ' node_id:', node_info.node_id, ' node_name:', node_info.node_name); 9 | global.node_info = node_info; 10 | global.timer.init(); 11 | 12 | for(var i = 0; i < node_info.endpoint_list.length; ++i) { 13 | if(node_info.endpoint_list[i].endpoint_type == Endpoint_Type.CONNECTOR) { 14 | util.sync_node_info(node_info.endpoint_list[i].endpoint_id); 15 | } 16 | } 17 | } 18 | 19 | function on_hotupdate(file_path) { } 20 | 21 | function on_drop_eid(eid) { 22 | util.sync_node_info(eid); 23 | } 24 | 25 | function on_drop_cid(cid) { } 26 | 27 | function on_msg(msg) {} 28 | 29 | function on_tick(timer_id) { 30 | var timer_handler = global.timer.get_timer_handler(timer_id); 31 | if (timer_handler != null) { 32 | timer_handler(); 33 | } 34 | } -------------------------------------------------------------------------------- /js/message.js: -------------------------------------------------------------------------------- 1 | if (typeof Msg == "undefined") { 2 | var Msg = {}; 3 | Msg.SYNC_NODE_CODE = 255; 4 | Msg.SYNC_SAVE_RUNTIME_DATA = 253; 5 | Msg.SYNC_LOAD_RUNTIME_DATA = 252; 6 | Msg.SYNC_DELETE_DB_DATA = 251; 7 | Msg.SYNC_SAVE_DB_DATA = 250; 8 | Msg.SYNC_LOAD_DB_DATA = 249; 9 | Msg.SYNC_RES_GENERATE_ID = 248; 10 | Msg.SYNC_GENERATE_ID = 247; 11 | Msg.SYNC_RES_SELECT_DB_DATA = 246; 12 | Msg.SYNC_SELECT_DB_DATA = 245; 13 | Msg.SYNC_DB_RET_CODE = 244; 14 | Msg.SYNC_PUBLIC_GAME_GUILD_INFO = 11; 15 | Msg.SYNC_SEND_MAIL = 10; 16 | Msg.SYNC_HOT_UPDATE = 9; 17 | Msg.SYNC_GATE_CENTER_REMOVE_SESSION = 8; 18 | Msg.SYNC_GAME_GATE_LOGOUT = 7; 19 | Msg.SYNC_GAME_PUBLIC_LOGIN_LOGOUT = 6; 20 | Msg.SYNC_GATE_GAME_ADD_SESSION = 5; 21 | Msg.SYNC_DELETE_RUNTIME_DATA = 254; 22 | Msg.SYNC_GATE_CENTER_VERIFY_TOKEN = 4; 23 | Msg.SYNC_NODE_STACK_INFO = 3; 24 | Msg.SYNC_NODE_STATUS = 2; 25 | Msg.SYNC_NODE_INFO = 1; 26 | Msg.HTTP_RES_STACK_INFO = 202; 27 | Msg.HTTP_RES_NODE_STATUS = 201; 28 | Msg.HTTP_SEND_MAIL = 5; 29 | Msg.HTTP_HOT_UPDATE = 4; 30 | Msg.HTTP_REQ_STACK_INFO = 3; 31 | Msg.HTTP_REQ_NODE_STATUS = 2; 32 | Msg.HTTP_CREATE_NODE_PROCESS = 1; 33 | Msg.RES_ERROR_CODE = 255; 34 | Msg.RES_TEST_SWITCH = 254; 35 | Msg.REQ_TEST_SWITCH = 254; 36 | Msg.RES_DISSOVE_GUILD = 202; 37 | Msg.REQ_DISSOVE_GUILD = 202; 38 | Msg.RES_CREATE_GUILD = 201; 39 | Msg.REQ_CREATE_GUILD = 201; 40 | Msg.RES_RESIGN_IN = 14; 41 | Msg.REQ_RESIGN_IN = 14; 42 | Msg.RES_SIGN_IN = 13; 43 | Msg.REQ_SIGN_IN = 13; 44 | Msg.RES_SEVEN_DAY_AWARD = 12; 45 | Msg.REQ_SEVEN_DAY_AWARD = 12; 46 | Msg.RES_DEL_MAIL = 11; 47 | Msg.REQ_DEL_MAIL = 11; 48 | Msg.RES_PICKUP_MAIL = 10; 49 | Msg.REQ_PICKUP_MAIL = 10; 50 | Msg.RES_MAIL_INFO = 9; 51 | Msg.REQ_MAIL_INFO = 9; 52 | Msg.RES_ROLE_INFO = 8; 53 | Msg.REQ_ROLE_INFO = 8; 54 | Msg.RES_DEL_ROLE = 7; 55 | Msg.REQ_DEL_ROLE = 7; 56 | Msg.REQ_CREATE_ROLE = 6; 57 | Msg.RES_ENTER_GAME = 5; 58 | Msg.REQ_ENTER_GAME = 5; 59 | Msg.RES_ROLE_LIST = 4; 60 | Msg.REQ_ROLE_LIST = 4; 61 | Msg.RES_CONNECT_GATE = 3; 62 | Msg.REQ_CONNECT_GATE = 3; 63 | Msg.RES_SELECT_GATE = 2; 64 | Msg.REQ_SELECT_GATE = 2; 65 | Msg.RES_HEARTBEAT = 1; 66 | Msg.REQ_HEARTBEAT = 1; 67 | } 68 | -------------------------------------------------------------------------------- /js/public_server/public_player.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 描述:public_player信息类 3 | * 作者:张亚磊 4 | * 时间:2016/03/26 5 | */ 6 | 7 | function Public_Player() { 8 | this.game_cid = 0; //玩家所在的game服务器cid 9 | this.sid = 0; //玩家sid 10 | this.role_info = null; //玩家信息 11 | } 12 | 13 | //玩家上线,加载数据 14 | Public_Player.prototype.login = function (game_cid, sid, role_info) { 15 | log_info("public_player login, sid:", sid, " role_id:", role_info.role_id, " role_name:", role_info.role_name, " game_cid:", game_cid); 16 | this.game_cid = game_cid; 17 | this.sid = sid; 18 | this.role_info = role_info; 19 | global.sid_public_player_map.set(this.sid, this); 20 | global.role_id_public_player_map.set(this.role_info.role_id, this); 21 | global.role_name_public_player_map.set(this.role_info.role_name, this); 22 | 23 | global.rank_manager.update_rank(Rank_Type.LEVEL_RANK, this); 24 | } 25 | 26 | //玩家离线,保存数据 27 | Public_Player.prototype.logout = function () { 28 | log_info("public_player logout, sid:", this.sid, " role_id:", this.role_info.role_id, " role_name:", this.role_info.role_name, " game_cid:", this.game_cid); 29 | global.sid_public_player_map.delete(this.sid); 30 | global.role_id_public_player_map.delete(this.role_info.role_id); 31 | global.role_name_public_player_map.delete(this.role_info.role_name); 32 | } 33 | 34 | Public_Player.prototype.send_msg = function(msg_id, msg) { 35 | send_msg(Endpoint.PUBLIC_SERVER, this.game_cid, msg_id, Msg_Type.NODE_S2C, this.sid, msg); 36 | } 37 | 38 | Public_Player.prototype.send_error_msg = function(error_code) { 39 | var msg = new Object(); 40 | msg.error_code = error_code; 41 | send_msg(Endpoint.PUBLIC_SERVER, this.game_cid, Msg.RES_ERROR_CODE, Msg_Type.NODE_S2C, this.sid, msg); 42 | } 43 | -------------------------------------------------------------------------------- /js/public_server/rank.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 描述:排行榜实现类 3 | * 作者:李俊良 4 | * 时间:2016/05/25 5 | */ 6 | 7 | function Rank_Manager() { 8 | this.rank_map = new Map(); 9 | } 10 | 11 | Rank_Manager.prototype.load_data = function(obj) { 12 | log_info('load rank data, size:', obj.rank_list.length); 13 | for(var i = 0; i < obj.rank_list.length; i++) { 14 | var rank_info = obj.rank_list[i]; 15 | log_info('rank type:', rank_info.rank_type, ' min_role_id:', rank_info.min_role_id); 16 | this.rank_map.set(rank_info.rank_type, rank_info); 17 | } 18 | } 19 | 20 | Rank_Manager.prototype.save_data = function() { 21 | var msg = new Object(); 22 | msg.save_type = Save_Type.SAVE_DB_AND_CACHE; 23 | msg.vector_data = true; 24 | msg.db_id = DB_Id.GAME; 25 | msg.struct_name = "Rank_Info"; 26 | msg.data_type = DB_Data_Type.RANK; 27 | msg.rank_list = new Array(); 28 | this.rank_map.forEach(function(value, key, map) { 29 | msg.rank_list.push(value); 30 | }); 31 | send_msg_to_db(Msg.SYNC_SAVE_DB_DATA, 0, msg); 32 | } 33 | 34 | Rank_Manager.prototype.get_rank_value = function(type, player) { 35 | //按照类型获取player对应数值 36 | var rank_value = 0; 37 | switch(type) { 38 | case Rank_Type.LEVEL_RANK: 39 | rank_value = player.role_info.level; 40 | break; 41 | case Rank_Type.COMBAT_RANK: 42 | rank_value = 1; 43 | break; 44 | default: 45 | rank_value = -1; 46 | break; 47 | } 48 | 49 | return rank_value; 50 | } 51 | 52 | Rank_Manager.prototype.update_rank = function(type, player) { 53 | var rank_info = this.rank_map.get(type); 54 | if(rank_info == null) { 55 | rank_info = new Object(); 56 | rank_info.rank_type = type; 57 | rank_info.min_role_id = player.role_info.role_id; 58 | rank_info.min_value = 0x7fffffff; 59 | rank_info.member_map = new Map(); 60 | this.rank_map.set(type, rank_info); 61 | } 62 | 63 | var rank_value = this.get_rank_value(type, player); 64 | var rank_member = rank_info.member_map.get(player.role_info.role_id); 65 | if(rank_member == null) { 66 | rank_member = new Object(); 67 | rank_member.role_id = player.role_info.role_id; 68 | rank_member.role_name = player.role_info.role_name; 69 | rank_member.value = rank_value; 70 | if(rank_info.member_map.size < 100) { 71 | rank_info.member_map.set(rank_member.role_id, rank_member); 72 | if(rank_member.value < rank_info.min_value){ 73 | rank_info.min_value = rank_member.value; 74 | rank_info.min_role_id = rank_member.role_id; 75 | } 76 | } 77 | else { 78 | if(rank_member.value > rank_info.min_value){ 79 | rank_info.member_map.delete(rank_info.min_role_id); 80 | rank_info.member_map.set(rank_member.role_id, rank_member); 81 | this.refresh_min_value(rank_info); 82 | } 83 | } 84 | } 85 | else { 86 | rank_member.value = rank_value; 87 | if(rank_member.value < rank_info.min_value){ 88 | rank_info.min_value = rank_member.value; 89 | rank_info.min_role_id = rank_member.role_id; 90 | } 91 | else { 92 | this.refresh_min_rank_value(rank_info); 93 | } 94 | } 95 | } 96 | 97 | Rank_Manager.prototype.refresh_min_rank_value = function(rank_info){ 98 | rank_info.min_value = 0x7fffffff; 99 | rank_info.member_map.forEach(function(value, key, map) { 100 | if(value.value < rank_info.min_value){ 101 | rank_info.min_value = value.value; 102 | rank_info.min_role_id = value.role_id; 103 | } 104 | }); 105 | } 106 | -------------------------------------------------------------------------------- /js/timer.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 描述:定时器系统 3 | * 作者:张亚磊 4 | * 时间:2016/10/24 5 | */ 6 | 7 | function Timer() { 8 | var timer_map = new Map(); 9 | var timer_id = 1; 10 | 11 | this.init = function() { 12 | //注册node_server定时器,时间间隔2s 13 | this.register_timer(2000, 0, this.node_server_handler); 14 | 15 | switch(global.node_info.node_type) { 16 | case Node_Type.CENTER_SERVER: { 17 | //注册清除token定时器,时间间隔2s 18 | this.register_timer(2000, 0, this.center_token_handler); 19 | break; 20 | } 21 | case Node_Type.GAME_SERVER: { 22 | //注册玩家定时器,时间间隔500ms 23 | this.register_timer(500, 0, this.game_player_handler); 24 | break; 25 | } 26 | case Node_Type.PUBLIC_SERVER: { 27 | //注册public定时器,时间间隔30s 28 | this.register_timer(30000, 0, this.public_server_handler); 29 | break; 30 | } 31 | default: { 32 | break; 33 | } 34 | } 35 | } 36 | 37 | this.register_timer = function(interval, next_tick, handler) { 38 | register_timer(timer_id, interval, next_tick); 39 | timer_map.set(timer_id, handler); 40 | timer_id++; 41 | } 42 | 43 | this.get_timer_handler = function(timer_id) { 44 | return timer_map.get(timer_id); 45 | } 46 | 47 | /////////////////////////////////定时器处理函数///////////////////////////////// 48 | this.node_server_handler = function() { 49 | switch(global.node_info.node_type) { 50 | case Node_Type.CENTER_SERVER: { 51 | for(var i = 0; i < global.master_list.length; ++i) { 52 | util.sync_node_status(Endpoint.CENTER_NODE_SERVER, global.master_list[i], 0); 53 | } 54 | break; 55 | } 56 | case Node_Type.GATE_SERVER: { 57 | util.sync_node_status(Endpoint.GATE_MASTER_CONNECTOR, 0, global.sid_session_map.size); 58 | break; 59 | } 60 | case Node_Type.DATA_SERVER: { 61 | util.sync_node_status(Endpoint.DATA_MASTER_CONNECTOR, 0, 0); 62 | break; 63 | } 64 | case Node_Type.LOG_SERVER: { 65 | util.sync_node_status(Endpoint.LOG_MASTER_CONNECTOR, 0, 0); 66 | break; 67 | } 68 | case Node_Type.MASTER_SERVER: { 69 | var node_status = util.get_node_status(); 70 | node_status.session_count = 0; 71 | global.node_status_map.set(node_status.node_id, node_status); 72 | break; 73 | } 74 | case Node_Type.PUBLIC_SERVER: { 75 | util.sync_node_status(Endpoint.PUBLIC_MASTER_CONNECTOR, 0, global.sid_public_player_map.size); 76 | break; 77 | } 78 | case Node_Type.GAME_SERVER: { 79 | util.sync_node_status(Endpoint.GAME_MASTER_CONNECTOR, 0, global.sid_game_player_map.size); 80 | break; 81 | } 82 | default: { 83 | break; 84 | } 85 | } 86 | } 87 | 88 | this.center_token_handler = function() { 89 | var now = util.now_sec(); 90 | global.account_token_map.forEach(function(value, key, map) { 91 | if (now - value.token_time >= 2) { 92 | on_close_session(key, value.cid, Error_Code.TOKEN_TIMEOUT); 93 | } 94 | }); 95 | } 96 | 97 | this.game_player_handler = function() { 98 | var now = util.now_sec(); 99 | global.role_id_game_player_map.forEach(function(value, key, map) { 100 | value.tick(now); 101 | }); 102 | } 103 | 104 | this.public_server_handler = function() { 105 | global.guild_manager.save_data_handler(); 106 | global.rank_manager.save_data(); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /js/util.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 描述:基础函数类 3 | * 作者:张亚磊 4 | * 时间:2016/03/15 5 | */ 6 | 7 | var util = function () {}; 8 | 9 | //一天的秒数 10 | util.whole_day_sec = 60 * 60 * 24; 11 | //一天的毫秒数 12 | util.whole_day_msec = util.whole_day_sec * 1000; 13 | 14 | //获取当前时间戳(秒单位) 15 | util.now_sec = function() { 16 | return Math.round(new Date().getTime()/1000); 17 | } 18 | 19 | //获取当前时间戳(毫秒单位) 20 | util.now_msec = function(date) { 21 | return new Date().getTime(); 22 | } 23 | 24 | //获取当前时间到指定定时时间的间隔(每日) 25 | util.get_next_day_tick = function(hour, min, sec) { 26 | var now = util.now_sec(); 27 | var date = new Date(); 28 | date.setHours(hour); 29 | date.setMinutes(min); 30 | date.setSeconds(sec); 31 | date.setMilliseconds(0); 32 | var time = date.getTime() / 1000; 33 | var next_tick = time - now; 34 | return next_tick > 0 ? next_tick : (next_tick + util.whole_day_sec); 35 | } 36 | 37 | util.sync_node_info = function(eid) { 38 | var msg = new Object(); 39 | msg.node_info = global.node_info; 40 | send_msg(eid, 0, Msg.SYNC_NODE_INFO, Msg_Type.NODE_MSG, 0, msg); 41 | } 42 | 43 | util.get_node_status = function() { 44 | var node_status = get_node_status(); 45 | var proc_info = get_proc_info(); 46 | var heap_info = get_heap_info(); 47 | var all_node_status = new Object(); 48 | //进程状态信息 49 | all_node_status.node_type = node_status.node_type; 50 | all_node_status.node_id = node_status.node_id; 51 | all_node_status.node_name = node_status.node_name; 52 | all_node_status.start_time = node_status.start_time; 53 | all_node_status.total_send = node_status.total_send; 54 | all_node_status.total_recv = node_status.total_recv; 55 | all_node_status.send_per_sec = node_status.send_per_sec; 56 | all_node_status.recv_per_sec = node_status.recv_per_sec; 57 | all_node_status.task_count = node_status.task_count; 58 | all_node_status.msg_list = node_status.msg_list; 59 | //获取cpu内存信息 60 | all_node_status.cpu_percent = proc_info.cpu_percent; 61 | all_node_status.vm_size = proc_info.vm_size; 62 | all_node_status.vm_rss = proc_info.vm_rss; 63 | all_node_status.vm_data = proc_info.vm_data; 64 | //获取v8堆信息 65 | all_node_status.heap_total = heap_info.heap_total; 66 | all_node_status.heap_used = heap_info.heap_used; 67 | all_node_status.external_mem = heap_info.external_mem; 68 | return all_node_status; 69 | } 70 | 71 | util.sync_node_status = function(eid, cid, session_count) { 72 | var msg = new Object(); 73 | msg.node_status = util.get_node_status(); 74 | msg.node_status.session_count = session_count; 75 | send_msg(eid, cid, Msg.SYNC_NODE_STATUS, Msg_Type.NODE_MSG, 0, msg); 76 | } 77 | 78 | util.calculate_distance = function(frm_pos, to_pos) { 79 | return Math.sqrt((to_pos.x - frm_pos.x) * (to_pos.x - frm_pos.x) + (to_pos.y - frm_pos.y) * (to_pos.y - frm_pos.y)); 80 | } 81 | 82 | util.abs = function(num) { 83 | if(num < 0) 84 | return -num; 85 | return num; 86 | } 87 | 88 | -------------------------------------------------------------------------------- /kill.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | pid=(`ps aux | grep 'daemon_server' | grep -v 'grep' | awk '{print $2}'`) 3 | if [ ! -n "$pid" ] 4 | then 5 | echo daemon_server process not found. 6 | else 7 | kill $pid 8 | echo daemon_server process[$pid] be killed. 9 | fi 10 | 11 | killall node_server 12 | 13 | de_servers=(`ps aux | grep 'node_server' | grep -v 'grep' | awk -F" " '{print \$2;}'`) 14 | count=${#node_servers[*]} 15 | 16 | if [ $count -gt 0 ] 17 | then 18 | for((i=0;i<$count;i++)) 19 | do 20 | kill ${node_servers[$i]} 21 | done 22 | else 23 | echo all node_server process be killed 24 | fi 25 | 26 | ps aux | grep node_server 27 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * main.cpp 3 | * Created on: Sep 19, 2016 4 | * Author: zhangyalei 5 | */ 6 | 7 | #include 8 | #include 9 | #include "Time_Value.h" 10 | #include "Node_Manager.h" 11 | 12 | static void sighandler(int sig_no) { exit(0); } //for gprof need normal exit 13 | 14 | struct option long_options[] = { 15 | {"label", required_argument, 0, 'l'}, 16 | {"node_type", required_argument, 0, 't'}, 17 | {"node_id", required_argument, 0, 'i'}, 18 | {"endpoint_gid", required_argument, 0, 'e'}, 19 | {"node_name", required_argument, 0, 'n'}, 20 | {0, 0, 0, 0} 21 | }; 22 | 23 | int parse_cmd_arguments(int argc, char *argv[]) { 24 | std::string label = ""; 25 | int node_type = 0; 26 | int node_id = 0; 27 | int endpoint_gid = 0; 28 | std::string node_name = ""; 29 | int c = 0; 30 | while ((c = getopt_long_only(argc, argv, "vdm:", long_options, NULL)) != -1) { 31 | switch (c) { 32 | case 'l': { //server_name 33 | label = optarg; 34 | break; 35 | } 36 | case 't': { //node_type 37 | node_type = atoi(optarg); 38 | break; 39 | } 40 | case 'i': { //node_id 41 | node_id = atoi(optarg); 42 | break; 43 | } 44 | case 'e': { //endpoint_gid 45 | endpoint_gid = atoi(optarg); 46 | break; 47 | } 48 | case 'n': { //node_name 49 | node_name = optarg; 50 | break; 51 | } 52 | default: { 53 | break; 54 | } 55 | } 56 | } 57 | 58 | if (node_type > 0 && node_id > 0) { 59 | LOG_WARN("node init, label:%s, node_type:%d, node_id:%d, endpoint_gid:%d, node_name:%s", label.c_str(), node_type, node_id, endpoint_gid, node_name.c_str()); 60 | NODE_MANAGER->init(node_type, node_id, endpoint_gid, node_name); 61 | } else { 62 | LOG_FATAL("node init, label:%s, node_type:%d, node_id:%d, endpoint_gid:%d, node_name:%s", label.c_str(), node_type, node_id, endpoint_gid, node_name.c_str()); 63 | } 64 | 65 | return 0; 66 | } 67 | 68 | int main(int argc, char *argv[]) { 69 | srand(Time_Value::gettimeofday().sec() + Time_Value::gettimeofday().usec()); 70 | srandom(Time_Value::gettimeofday().sec() + Time_Value::gettimeofday().usec()); 71 | signal(SIGPIPE, SIG_IGN); 72 | signal(SIGUSR1, sighandler); 73 | 74 | if(parse_cmd_arguments(argc, argv) == 0) { 75 | Epoll_Watcher watcher; 76 | watcher.loop(); 77 | } 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /make_plugin.sh: -------------------------------------------------------------------------------- 1 | cd plugin 2 | cd aoi && make 3 | cd ../ 4 | cd db && make 5 | cd ../ 6 | cd gate && make 7 | cd ../ 8 | cd log && make 9 | cd ../ 10 | cd monitor && make 11 | cd ../../ 12 | 13 | -------------------------------------------------------------------------------- /node_server.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | 14 | {A286AD1C-17D1-4494-BF89-E92F3121EDEA} 15 | MakeFileProj 16 | node_server 17 | 18 | 19 | 20 | Makefile 21 | true 22 | v110 23 | 24 | 25 | Makefile 26 | false 27 | v110 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | WIN32;_DEBUG;$(NMakePreprocessorDefinitions) 41 | 42 | 43 | WIN32;NDEBUG;$(NMakePreprocessorDefinitions) 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /node_server.vcxproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | true 5 | 6 | -------------------------------------------------------------------------------- /nodelib/Makefile: -------------------------------------------------------------------------------- 1 | ############################################################################## 2 | # # 3 | # 默认为release模式编译,debug模式请使用参数'MODE=DEBUG' # 4 | # 默认不编译MongoDB功能,想编译的话请使用参数'MONGO=TRUE' # 5 | # # 6 | ############################################################################## 7 | 8 | ###在这里添加源文件目录### 9 | SRCDIR= ./\ 10 | ./base/\ 11 | ./db/\ 12 | ./network/\ 13 | ./node/\ 14 | ./struct/\ 15 | ./v8/\ 16 | ./xml/ 17 | 18 | ###这里定义目标文件目录### 19 | OBJDIR =./.obj/ 20 | 21 | TARGET_NAME=libnodelib.so 22 | 23 | BIN=./ 24 | 25 | INCLUDE=$(addprefix -I, $(SRCDIR)) 26 | 27 | LIBDIR=-L./ 28 | 29 | LIB=-lv8\ 30 | -lv8_libplatform\ 31 | -lcurl\ 32 | -lcrypto\ 33 | -ldl\ 34 | -lz\ 35 | -ljsoncpp\ 36 | -lmysqlcppconn\ 37 | $(MONGO_LIB) 38 | 39 | CC=g++ 40 | 41 | DEPENDS=-MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" 42 | 43 | ifeq ($(MODE), DEBUG) 44 | BUILD_FLAG = -O0 -g3 45 | else 46 | BUILD_FLAG = -O3 47 | endif 48 | 49 | ifeq ($(MONGO), TRUE) 50 | CONDITION=-D MONGO_DB_IMPLEMENT 51 | MONGO_LIB=-lmongoclient\ 52 | -lboost_filesystem\ 53 | -lboost_thread-mt 54 | else 55 | CONDITION= 56 | MONGO_LIB= 57 | endif 58 | 59 | COM_FLAG=-Wall -fPIC -shared -c -fmessage-length=0 -std=c++11 60 | 61 | LDFLAG=-shared 62 | 63 | BIN_TARGET=$(OBJDIR)bin/$(TARGET_NAME) 64 | 65 | SRCS=$(wildcard $(addsuffix *.cpp, $(SRCDIR))) 66 | 67 | OBJECTS:=$(addprefix $(OBJDIR), $(subst ./,,$(SRCS:.cpp=.o))) 68 | 69 | .PHONY:all mkobjdir clean config 70 | 71 | all:mkobjdir $(BIN_TARGET) 72 | 73 | -include $(OBJECTS:.o=.d) 74 | 75 | $(BIN_TARGET):$(OBJECTS) 76 | $(CC) $(LDFLAG) -o $@ $^ $(LIBDIR) $(LIB) 77 | @echo " " 78 | @echo "Finished building target: $(TARGET_NAME)" 79 | @echo " " 80 | @-cp -f $(BIN_TARGET) $(BIN) 81 | 82 | $(OBJDIR)%.o:%.cpp 83 | ifeq ($(MODE), DEBUG) 84 | @echo "Building DEBUG MODE target $@" 85 | else 86 | @echo "Building RELEASE MODE target $@" 87 | endif 88 | $(CC) $(INCLUDE) $(BUILD_FLAG) $(COM_FLAG) $(DEPENDS) $(CONDITION) -o "$(@)" "$(<)" 89 | @echo " " 90 | 91 | mkobjdir: 92 | @test -d $(OBJDIR) || (mkdir $(OBJDIR) && mkdir $(OBJDIR)bin $(addprefix $(OBJDIR), $(subst ./,,$(SRCDIR)))) 93 | 94 | clean: 95 | -rm -rf $(OBJDIR) -------------------------------------------------------------------------------- /nodelib/base/Aes.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/nodelib/base/Aes.cpp -------------------------------------------------------------------------------- /nodelib/base/Aes.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/nodelib/base/Aes.h -------------------------------------------------------------------------------- /nodelib/base/Base_Define.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Base_Define.cpp 3 | * 4 | * Created on: Sep 22, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "Bit_Buffer.h" 9 | #include "Byte_Buffer.h" 10 | #include "Base_Define.h" 11 | 12 | void Endpoint_Info::serialize(Bit_Buffer &buffer) { 13 | buffer.write_int(endpoint_type, 32); 14 | buffer.write_int(endpoint_gid, 32); 15 | buffer.write_int(endpoint_id, 32); 16 | buffer.write_str(endpoint_name.c_str()); 17 | buffer.write_str(server_ip.c_str()); 18 | buffer.write_int(server_port, 32); 19 | buffer.write_int(protocol_type, 32); 20 | buffer.write_int(heartbeat_timeout, 32); 21 | } 22 | 23 | void Endpoint_Info::deserialize(Bit_Buffer &buffer) { 24 | endpoint_type = buffer.read_int(32); 25 | endpoint_gid = buffer.read_int(32); 26 | endpoint_id = buffer.read_int(32); 27 | buffer.read_str(endpoint_name); 28 | buffer.read_str(server_ip); 29 | server_port = buffer.read_int(32); 30 | protocol_type = buffer.read_int(32); 31 | heartbeat_timeout = buffer.read_int(32); 32 | } 33 | 34 | void Endpoint_Info::reset(void) { 35 | endpoint_type = 0; 36 | endpoint_gid = 0; 37 | endpoint_id = 0; 38 | endpoint_name = ""; 39 | server_ip = ""; 40 | server_port = 0; 41 | protocol_type = 0; 42 | heartbeat_timeout = 0; 43 | } 44 | 45 | void Buffer_Group_Info::serialize(Bit_Buffer &buffer) { 46 | buffer.write_int(free_size, 32); 47 | buffer.write_int(used_size, 32); 48 | buffer.write_int(sum_bytes, 32); 49 | } 50 | 51 | void Buffer_Group_Info::deserialize(Bit_Buffer &buffer) { 52 | free_size = buffer.read_int(32); 53 | used_size = buffer.read_int(32); 54 | sum_bytes = buffer.read_int(32); 55 | } 56 | 57 | void Buffer_Group_Info::reset(void) { 58 | free_size = 0; 59 | used_size = 0; 60 | sum_bytes = 0; 61 | } 62 | 63 | void Svc_Info::serialize(Bit_Buffer &buffer) { 64 | buffer.write_int(endpoint_gid, 32); 65 | buffer.write_int(endpoint_id, 32); 66 | buffer.write_int(svc_pool_free_size, 32); 67 | buffer.write_int(svc_pool_used_size, 32); 68 | buffer.write_int(svc_list_size, 32); 69 | 70 | uint16_t size = buffer_group_list.size(); 71 | buffer.write_uint(size, 16); 72 | for (uint16_t i = 0; i < size; ++i) { 73 | buffer_group_list[i].serialize(buffer); 74 | } 75 | } 76 | 77 | void Svc_Info::deserialize(Bit_Buffer &buffer) { 78 | endpoint_gid = buffer.read_int(32); 79 | endpoint_id = buffer.read_int(32); 80 | svc_pool_free_size = buffer.read_int(32); 81 | svc_pool_used_size = buffer.read_int(32); 82 | svc_list_size = buffer.read_int(32); 83 | 84 | uint16_t size = buffer.read_uint(16); 85 | Buffer_Group_Info group_info; 86 | for (uint16_t i = 0; i < size; ++i) { 87 | group_info.reset(); 88 | group_info.deserialize(buffer); 89 | buffer_group_list.push_back(group_info); 90 | } 91 | } 92 | 93 | void Svc_Info::reset(void) { 94 | endpoint_gid = 0; 95 | endpoint_id = 0; 96 | svc_pool_free_size = 0; 97 | svc_pool_used_size = 0; 98 | svc_list_size = 0; 99 | buffer_group_list.clear(); 100 | } 101 | -------------------------------------------------------------------------------- /nodelib/base/Base_Define.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Base_Define.h 3 | * 4 | * Created on: Sep 22, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef BASE_DEFINE_H_ 9 | #define BASE_DEFINE_H_ 10 | 11 | #include 12 | #include "Time_Value.h" 13 | 14 | struct Data_Info { 15 | int file_size; 16 | int data_len; 17 | char* data; 18 | } ; 19 | 20 | struct Msg_Head { 21 | int32_t eid; 22 | int32_t cid; 23 | uint8_t protocol; 24 | uint8_t pkg_type; 25 | uint8_t client_msg; 26 | uint8_t msg_id; 27 | uint8_t msg_type; 28 | uint32_t sid; 29 | 30 | Msg_Head() { reset(); } 31 | void reset() { 32 | eid = 0; 33 | cid = 0; 34 | protocol = 0; 35 | pkg_type = 0; 36 | client_msg = 0; 37 | msg_id = 0; 38 | msg_type = 0; 39 | sid = 0; 40 | } 41 | }; 42 | 43 | struct Field_Info { 44 | std::string field_label; //字段标签 45 | std::string field_type; //字段类型 46 | int field_bit; //字段位数 47 | std::string field_name; //字段名称 48 | int field_vbit; //数组字段长度位数 49 | uint case_val; //case标签对应的值 50 | std::string key_type; //主键类型 51 | int key_bit; //主键位数 52 | std::string key_name; //主键名称 53 | std::vector children;//if/switch使用存放子字段 54 | 55 | Field_Info() { reset(); } 56 | void reset() { 57 | field_label = ""; 58 | field_vbit = 0; 59 | case_val = 0; 60 | field_type = ""; 61 | field_bit = 0; 62 | field_name = ""; 63 | key_type = ""; 64 | key_bit = 0; 65 | key_name = ""; 66 | children.clear(); 67 | } 68 | }; 69 | typedef std::vector Field_Vec; 70 | 71 | class Bit_Buffer; 72 | class Byte_Buffer; 73 | struct Endpoint_Info { 74 | int endpoint_type; //端点类型 75 | int endpoint_gid; //端点组id 76 | int endpoint_id; //端点id 77 | std::string endpoint_name; //端点名称 78 | std::string server_ip; //服务器ip 79 | int server_port; //服务器端口(如果是connect端点,该ip和port表示它要连接的服务器) 80 | int protocol_type; //网络协议类型 0:Tcp 1:Udp 2:Websocket 3:Http 81 | int heartbeat_timeout; //心跳超时时间 单位:s 82 | 83 | void serialize(Bit_Buffer &buffer); 84 | void deserialize(Bit_Buffer &buffer); 85 | void reset(void); 86 | }; 87 | 88 | struct Buffer_Group_Info { 89 | int free_size; //buffer对象池未使用节点数量 90 | int used_size; //buffer对象池已使用节点数量 91 | int sum_bytes; //对象池总共大小 92 | 93 | void serialize(Bit_Buffer &buffer); 94 | void deserialize(Bit_Buffer &buffer); 95 | void reset(void); 96 | }; 97 | 98 | struct Svc_Info { 99 | int endpoint_gid; //端点组id 100 | int endpoint_id; //端点id 101 | int svc_pool_free_size; //svc对象池未使用节点数量 102 | int svc_pool_used_size; //svc对象池已使用节点数量 103 | int svc_list_size; //svc列表数量 104 | std::vector buffer_group_list; 105 | 106 | void serialize(Bit_Buffer &buffer); 107 | void deserialize(Bit_Buffer &buffer); 108 | void reset(void); 109 | }; 110 | 111 | #endif /* BASE_DEFINE_H_ */ 112 | -------------------------------------------------------------------------------- /nodelib/base/Base_Enum.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Base_Enum.h 3 | * 4 | * Created on: Sep 20, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef BASE_ENUM_H_ 9 | #define BASE_ENUM_H_ 10 | 11 | //node命名管道路径 12 | #define NODE_FIFO "/tmp/node_fifo" 13 | 14 | //包是否压缩 15 | #define IS_PACKAGE_COMPRESSED(l) ((l)&(0x1<<5)) 16 | 17 | //rpc package header size: 2bytes, length: 13bits, 0-8191 bytes 18 | #define MAKE_RPC_PKG_HEADER(l,comp) (RPC_PKG << 6 | ((comp&0x1)<<5) | (((l)&0x1f00)>>8) | (((l)&0x00ff)<<8)) 19 | #define GET_RPC_PKG_LENGTH(h,l) ((((h)&0x1f)<<8) | (((l)&0xff00)>>8)) 20 | 21 | //type package header size: 4bytes, length: 29bits, 0-536870911 bytes 22 | #define MAKE_TYPE_PKG_HEADER(l,comp) (TYPE_PKG << 6 | ((comp&0x1)<<5) | (((l)&0x1f000000)>>24) | (((l)&0x00ffffff)<<8)) 23 | #define GET_TYPE_PKG_LENGTH(h,l) ((((h)&0x1f)<<24) | (((l)&0xffffff00)>>8)) 24 | 25 | enum Protocol_Type { 26 | TCP = 1, 27 | UDP = 2, 28 | HTTP = 3, 29 | WEBSOCKET = 4, 30 | }; 31 | 32 | enum Package_Type 33 | { 34 | RPC_PKG = 1, //rpc包,协议定义写到配置文件,包长最多2^13-1个字节 35 | TYPE_PKG = 2, //type包,协议定义写到包里,包长最多2^29-1个字节 36 | }; 37 | 38 | enum Endpoint_Type { 39 | CLIENT_SERVER = 1, //接受客户端链接的server 40 | SERVER = 2, //接受内部节点连接的server 41 | CONNECTOR = 3, //内部节点链接器 42 | }; 43 | 44 | enum Msg_Type { 45 | TCP_C2S = 1, //客户端发到服务器的消息 46 | TCP_S2C = 2, //服务器发到客户端的消息 47 | NODE_C2S = 3, //客户端经过gate中转发到服务器的消息 48 | NODE_S2C = 4, //服务器经过gate中转发到客户端的消息 49 | NODE_MSG = 5, //服务器进程节点间通信的消息 50 | DATA_MSG = 6, //经过data中转发到data子进程的消息 51 | HTTP_MSG = 7, //http消息 52 | WS_C2S = 8, //websocket客户端消息 53 | WS_S2C = 9, //websocket服务器消息 54 | }; 55 | 56 | enum Event_Type { 57 | EVENT_INPUT = 0x1, 58 | EVENT_OUTPUT = 0x2, 59 | EVENT_TIMEOUT = 0x4, 60 | EVENT_ONCE_IO_IN = 0x8, //一次性IO输入事件 61 | EVENT_ONCE_IO_OUT = 0x10, //一次性IO输出事件 62 | EVENT_ONCE_TIMER = 0x20, //一次性定时器事件 63 | WITH_IO_HEARTBEAT = 0x40, //IO附带心跳机制 64 | }; 65 | 66 | enum Log_Type { 67 | LOG_DEBUG = 1, //细粒度信息事件对调试应用程序是非常有帮助的 68 | LOG_INFO = 2, //消息在粗粒度级别上突出强调应用程序的运行过程 69 | LOG_WARN = 3, //会出现潜在错误的情形 70 | LOG_ERROR = 4, //虽然发生错误事件,但仍然不影响系统的继续运行 71 | LOG_TRACE = 5, //打印程序运行堆栈,跟踪记录数据信息 72 | LOG_FATAL = 6, //严重的错误事件,将会导致应用程序的退出 73 | }; 74 | 75 | enum Color { 76 | BLACK = 30, 77 | RED = 31, 78 | GREEN = 32, 79 | BROWN = 33, 80 | BLUE = 34, 81 | MAGENTA = 35, 82 | CYAN = 36, 83 | GREY = 37, 84 | LRED = 41, 85 | LGREEN = 42, 86 | YELLOW = 43, 87 | LBLUE = 44, 88 | LMAGENTA = 45, 89 | LCYAN = 46, 90 | WHITE = 47 91 | }; 92 | 93 | enum Websocket_Frame { 94 | FRAME_NORMAL = 0x0, 95 | FRAME_FINAL = 0x1, 96 | }; 97 | 98 | enum Websocket_Opcode { 99 | OPCODE_CONTINUATION = 0x0, 100 | OPCODE_TEXT = 0x1, 101 | OPCODE_BINARY = 0x2, 102 | OPCODE_CLOSE = 0x8, 103 | OPCODE_PING = 0x9, 104 | OPCODE_PONG = 0xa, 105 | }; 106 | 107 | enum Struct_Type { 108 | BASE_STRUCT = 1, //基本结构体 109 | MSG_STRUCT = 2, //消息结构体 110 | ROBOT_STRUCT = 3, //robot结构体 111 | DB_STRUCT = 4, //数据库结构体 112 | }; 113 | 114 | enum DB_Type { 115 | MYSQL = 1, 116 | MONGO = 2, 117 | }; 118 | 119 | enum Save_Type { 120 | SAVE_CACHE = 1, //保存缓存 121 | SAVE_DB_AND_CACHE = 2, //保存数据库和缓存 122 | SAVE_DB_CLEAR_CACHE = 3, //保存数据库清空缓存 123 | }; 124 | 125 | #endif /* ENUM_H_ */ 126 | -------------------------------------------------------------------------------- /nodelib/base/Base_Function.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/nodelib/base/Base_Function.cpp -------------------------------------------------------------------------------- /nodelib/base/Base_Function.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Comm_Func.h 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef COMMON_FUNC_H_ 9 | #define COMMON_FUNC_H_ 10 | 11 | #include 12 | #include 13 | #include 14 | #include "Base_Enum.h" 15 | #include "Date_Time.h" 16 | 17 | //设置fd为非阻塞模式 18 | void set_nonblock(int fd); 19 | //获取进程最大fd 20 | int max_fd(void); 21 | //设置进程资源限制 22 | void set_rlimit(); 23 | 24 | //定义文件处理函数指针,该函数参数是char*,返回值是int 25 | typedef int (*file_handler) (const char *); 26 | //遍历文件夹 27 | int read_folder(const char *folder_path, file_handler handler); 28 | 29 | //从fifo里面读数据 30 | int read_fifo(const char *fifo_path, void *buf, int count); 31 | //往fifo里面写数据 32 | int write_fifo(const char *fifo_path, const void *buf, int count); 33 | 34 | //获得进程调用堆栈 35 | void backstrace_string(std::string &res); 36 | //字符串分割 37 | std::vector split(const std::string &str, const std::string &pattern); 38 | //获取字符串类型 返回值:-1表示字符串为空,0表示字符串,1表示整数,2表示小数 39 | int get_string_type(const char *str); 40 | 41 | //设置控制台颜色 42 | void set_color(int fd, Color color); 43 | void reset_color(int fd); 44 | 45 | //返回大于1.5 * num的第一个素数 46 | size_t get_hash_table_size(unsigned int num); 47 | //获得elf hash值 48 | int64_t elf_hash(const char *str); 49 | //生成全局唯一id 50 | int64_t make_id(int first_num, int second_num, int idx); 51 | //生成token值 52 | std::string make_token(const char *str); 53 | //校验md5值 54 | int validate_md5(const char *key, const char *account, const char *time, const char *flag); 55 | 56 | //设置时间 57 | void set_date_to_day(Date_Time &date_time, int time); 58 | void set_date_time(Date_Time &date_time, int time); 59 | void set_date_to_hour(Date_Time &date_time, int time); 60 | //获取明天0点时间戳 61 | int get_time_zero(void); 62 | //获取指定时间的零点时间戳(不是24点) 63 | int get_zero_time(const int sec); 64 | int get_today_zero(void); 65 | int set_time_to_zero(const Time_Value &time_src, Time_Value &time_des); 66 | //获取星期日零点时间戳 67 | int get_sunday_time_zero(void); 68 | Time_Value get_week_time(int week, int hour = 0, int minute = 0, int second = 0); 69 | // 获取的是相对时间 70 | Time_Value spec_next_day_relative_time(int hour, int minute, int second); 71 | // 获取的是绝对时间 72 | Time_Value spec_today_absolute_time(unsigned int hour, unsigned int minute, unsigned int second); 73 | Time_Value get_day_begin(const Time_Value &now); 74 | void get_next_cycle_time(const Time_Value &begin, const Time_Value &now, const Time_Value &offset, const Time_Value &cycle, Time_Value &next_time); 75 | void get_date_day_gap(const Time_Value &date1, const Time_Value &date2, int &day); 76 | //get_days_delta:获取两个时间之间相差的天数(此天数以日期的天为单位),即1号的任意钟头和2号的任意钟头都是相差一天 77 | int get_days_delta(Time_Value time1, Time_Value time2); 78 | 79 | //数字比较函数 80 | inline int max(int first, int second) { return first >= second ? first : second; } 81 | inline int min(int first, int second) { return first <= second ? first : second; } 82 | inline bool is_double_zero(double value) { return value >= -0.0000001 && value <= 0.0000001; } 83 | inline bool is_double_gt_zero(double value) { return value > 0.0000001; } 84 | inline bool is_double_lt_zero(double value) { return value < -0.0000001; } 85 | 86 | //base64编码解码 87 | inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } 88 | std::string base64_encode(unsigned char const* , unsigned int len); 89 | std::string base64_decode(std::string const& s); 90 | 91 | #endif /* COMMON_FUNC_H_ */ 92 | -------------------------------------------------------------------------------- /nodelib/base/Buffer_Pool_Group.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Buffer_Pool_Group.h 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef BUFFER_POOL_GROUP_H_ 9 | #define BUFFER_POOL_GROUP_H_ 10 | 11 | #include 12 | #include "Byte_Buffer.h" 13 | #include "Object_Pool.h" 14 | 15 | class Buffer_Pool_Group { 16 | public: 17 | typedef Object_Pool Buffer_Pool; 18 | typedef std::vector Pool_Group; 19 | 20 | Buffer_Pool_Group(size_t group_size = 1) 21 | : group_size_(group_size), x_(0) { 22 | init(); 23 | } 24 | 25 | virtual ~Buffer_Pool_Group(void) { 26 | fini(); 27 | } 28 | 29 | int init(void) { 30 | pool_group_.clear(); 31 | 32 | Buffer_Pool *pool = 0; 33 | for (size_t i = 0; i < group_size_; ++i) { 34 | if ((pool = new Buffer_Pool) == 0) { 35 | LOG_FATAL("new return 0"); 36 | } 37 | pool_group_.push_back(pool); 38 | } 39 | return 0; 40 | } 41 | 42 | int fini(void) { 43 | for (Pool_Group::iterator it = pool_group_.begin(); it != pool_group_.end(); ++it) { 44 | (*it)->clear(); 45 | } 46 | pool_group_.clear(); 47 | return 0; 48 | } 49 | 50 | Byte_Buffer *pop_buffer(int cid) { 51 | return pool_group_[cid % group_size_]->pop(); 52 | } 53 | 54 | int push_buffer(int cid, Byte_Buffer *buffer) { 55 | if (!buffer) { 56 | LOG_TRACE("buffer == 0"); 57 | return -1; 58 | } 59 | buffer->recycle_space(); 60 | return pool_group_[cid % group_size_]->push(buffer); 61 | } 62 | 63 | void shrink_all(void) { 64 | for (size_t i = 0; i < group_size_; ++i) { 65 | pool_group_[i]->shrink_all(); 66 | } 67 | } 68 | 69 | void dump_info(void) { 70 | for (size_t i = 0; i < group_size_; ++i) { 71 | LOG_DEBUG("***pool_group_[%u]: ", i); 72 | pool_group_[i]->debug_info(); 73 | } 74 | } 75 | 76 | void dump_size(void) { 77 | size_t sum_size = 0; 78 | for (Pool_Group::iterator group_it = pool_group_.begin(); group_it != pool_group_.end(); ++group_it) { 79 | sum_size += (* group_it)->sum_size(); 80 | } 81 | } 82 | 83 | void get_buffer_group(std::vector &group_list) { 84 | Buffer_Group_Info group_info; 85 | for (size_t i = 0; i < group_size_; ++i) { 86 | group_info.free_size = pool_group_[i]->free_obj_list_size(); 87 | group_info.used_size = pool_group_[i]->used_obj_list_size(); 88 | group_info.sum_bytes = pool_group_[i]->sum_size(); 89 | group_list.push_back(group_info); 90 | } 91 | } 92 | 93 | private: 94 | Pool_Group pool_group_; 95 | size_t group_size_; 96 | int x_; 97 | }; 98 | 99 | #endif /* BUFFER_POOL_GROUP_H_ */ 100 | -------------------------------------------------------------------------------- /nodelib/base/Compress.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/nodelib/base/Compress.cpp -------------------------------------------------------------------------------- /nodelib/base/Compress.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/nodelib/base/Compress.h -------------------------------------------------------------------------------- /nodelib/base/Config.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Config.cpp 3 | * 4 | * Created on: Mar 1,2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "Log.h" 15 | 16 | Config::Config(void) { } 17 | 18 | Config::~Config(void) { } 19 | 20 | int Config::load_json_file(const char *file_path, Json::Value &conf_value) { 21 | int fd = 0; 22 | if ((fd = open(file_path, O_RDONLY)) < 0) { 23 | LOG_FATAL("Failed to open file %s\n error: %s\n.\n", file_path, reader_.getFormatedErrorMessages().c_str()); 24 | } 25 | 26 | struct stat statbuf; 27 | if (fstat(fd, &statbuf) < 0) { 28 | LOG_FATAL("fstat error file %s\n", file_path); 29 | } 30 | 31 | void *src = 0; 32 | if ((src = mmap(0, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) { 33 | LOG_FATAL("mmap error file %s\n", file_path); 34 | } 35 | 36 | if (! reader_.parse(static_cast(src), static_cast(src) + statbuf.st_size, conf_value)) { 37 | LOG_FATAL("Failed to parse file %s\n error: %s\n.\n", file_path, reader_.getFormatedErrorMessages().c_str()); 38 | } 39 | 40 | if (munmap(src, statbuf.st_size) < 0) { 41 | LOG_FATAL("munmap error file %s\n", file_path); 42 | } 43 | 44 | close(fd); 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /nodelib/base/Config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Config.h 3 | * 4 | * Created on: Mar 1,2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef CONFIG_H_ 9 | #define CONFIG_H_ 10 | 11 | #include "json/json.h" 12 | #include 13 | #include "Thread_Guard.h" 14 | 15 | class Config { 16 | public: 17 | typedef RE_LOCK Config_Lock; 18 | typedef std::unordered_map Config_Map; 19 | typedef std::unordered_map Int_Json_Map; 20 | typedef void (*JsonKey_Func)(const Json::Value &json, int &key); 21 | 22 | struct Config_Entry { 23 | Config_Entry(void) : cur_version(0) { } 24 | 25 | inline void cover_cur_json_to_map(void) { 26 | get_cur_map_json().clear(); 27 | for (Json::Value::iterator it = get_cur_json().begin(); it != get_cur_json().end(); ++it) 28 | get_cur_map_json().insert(std::make_pair(atoi(it.key().asCString()), *it)); 29 | } 30 | inline void cover_next_json_to_map(void) { 31 | get_next_map_json().clear(); 32 | for (Json::Value::iterator it = get_next_json().begin(); it != get_next_json().end(); ++it) 33 | get_next_map_json().insert(std::make_pair(atoi(it.key().asCString()), *it)); 34 | } 35 | 36 | inline int get_cur_version(void) { return cur_version; } 37 | inline int get_next_version(void) { 38 | return (!cur_version); 39 | } 40 | 41 | inline void update_version(void) { 42 | cur_version = (cur_version + 1) % 2; 43 | } 44 | 45 | inline Json::Value &get_cur_json(void) { return json[get_cur_version()]; } 46 | inline Json::Value &get_next_json(void) { return json[get_next_version()]; } 47 | 48 | inline Int_Json_Map &get_cur_map_json(void) { return json_map[get_cur_version()]; } 49 | inline Int_Json_Map &get_next_map_json(void) { return json_map[get_next_version()]; } 50 | 51 | inline void clear_cur_json(void) { json[get_cur_version()].clear(); } 52 | inline void clear_next_json(void) { json[get_next_version()].clear(); } 53 | 54 | Json::Value json[2]; 55 | Int_Json_Map json_map[2]; 56 | int cur_version; 57 | }; 58 | 59 | public: 60 | Config(void); 61 | virtual ~Config(void); 62 | 63 | int load_json_file(const char *file_path, Json::Value &conf_value); 64 | inline const Json::Value &get_json_value_in_map(const int id, Config_Entry &config); 65 | inline const Json::Value &get_json_value_with_rlock(Config_Lock &lock, Config_Entry &config); 66 | inline const Json::Value &get_json_value_with_rlock_in_map(Config_Lock &lock, const int id, Config_Entry &config); 67 | 68 | private: 69 | Json::Reader reader_; 70 | }; 71 | 72 | /////////////////////////////////////////////////////////////////////////////// 73 | inline const Json::Value &Config::get_json_value_in_map(const int id, Config_Entry &config) { 74 | Int_Json_Map &map = config.get_cur_map_json(); 75 | Int_Json_Map::const_iterator it = map.find(id); 76 | if (it != map.end()) { 77 | return it->second; 78 | } else { 79 | return Json::Value::null; 80 | } 81 | } 82 | 83 | inline const Json::Value &Config::get_json_value_with_rlock_in_map(Config_Lock &lock, const int id, Config_Entry &config) { 84 | GUARD_READ(Config_Lock, mon, lock); 85 | return get_json_value_in_map(id, config); 86 | } 87 | 88 | inline const Json::Value &Config::get_json_value_with_rlock(Config_Lock &lock, Config_Entry &config) { 89 | GUARD_READ(Config_Lock, mon, lock); 90 | return config.get_cur_json(); 91 | } 92 | 93 | #endif /* CONFIG_H_ */ 94 | -------------------------------------------------------------------------------- /nodelib/base/Date_Time.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * DateTime.cpp 3 | * 4 | * Created on: Jan 12,2016 5 | * Author: "zhangyalei" 6 | */ 7 | 8 | #include "Date_Time.h" 9 | 10 | Date_Time::Date_Time(void) : day_(0), month_(0), year_(0), hour_(0), minute_(0), second_(0), microsec_(0), wday_(0) { 11 | this->update (); 12 | } 13 | 14 | 15 | Date_Time::Date_Time(const Time_Value &timevalue) : day_(0), month_(0), year_(0), hour_(0), minute_(0), second_(0), microsec_(0), wday_(0){ 16 | this->update (timevalue); 17 | } 18 | 19 | Date_Time::Date_Time(long day, long month, long year, long hour, long minute, long second, long microsec, long wday) 20 | : day_ (day), month_ (month), year_ (year), hour_ (hour), minute_ (minute), second_ (second), microsec_ (microsec), wday_ (wday) { 21 | 22 | } 23 | 24 | void Date_Time::update(void) { 25 | update(Time_Value::gettimeofday ()); 26 | } 27 | 28 | void Date_Time::update(const Time_Value &timevalue) { 29 | time_t time = timevalue.sec(); 30 | struct tm tm_time; 31 | ::localtime_r(&time, &tm_time); 32 | this->day_ = tm_time.tm_mday; 33 | this->month_ = tm_time.tm_mon + 1; // localtime's months are 0-11 34 | this->year_ = tm_time.tm_year + 1900; // localtime reports years since 1900 35 | this->hour_ = tm_time.tm_hour; 36 | this->minute_ = tm_time.tm_min; 37 | this->second_ = tm_time.tm_sec; 38 | this->microsec_ = timevalue.usec(); 39 | this->wday_ = tm_time.tm_wday; 40 | } 41 | 42 | long Date_Time::day(void) const { 43 | return day_; 44 | } 45 | 46 | void Date_Time::day(long day) { 47 | day_ = day; 48 | } 49 | 50 | long Date_Time::month(void) const { 51 | return month_; 52 | } 53 | 54 | void Date_Time::month(long month) { 55 | month_ = month; 56 | } 57 | 58 | long Date_Time::year(void) const { 59 | return year_; 60 | } 61 | 62 | void Date_Time::year(long year) { 63 | year_ = year; 64 | } 65 | 66 | long Date_Time::hour(void) const { 67 | return hour_; 68 | } 69 | 70 | void Date_Time::hour(long hour) { 71 | hour_ = hour; 72 | } 73 | 74 | long Date_Time::minute(void) const { 75 | return minute_; 76 | } 77 | 78 | void Date_Time::minute(long minute) { 79 | minute_ = minute; 80 | } 81 | 82 | long Date_Time::second(void) const { 83 | return second_; 84 | } 85 | 86 | void Date_Time::second(long second) { 87 | second_ = second; 88 | } 89 | 90 | long Date_Time::microsec(void) const { 91 | return microsec_; 92 | } 93 | 94 | void Date_Time::microsec(long microsec) { 95 | microsec_ = microsec; 96 | } 97 | 98 | long Date_Time::weekday(void) const { 99 | return wday_; 100 | } 101 | 102 | void Date_Time::weekday(long wday) { 103 | wday_ = wday; 104 | } 105 | 106 | time_t Date_Time::time_sec(void) { 107 | struct tm t; 108 | t.tm_year = year_ - 1900; 109 | t.tm_mon = month_ - 1; 110 | t.tm_mday = day_; 111 | t.tm_hour = hour_; 112 | t.tm_min = minute_; 113 | t.tm_sec = second_; 114 | t.tm_isdst = 0; 115 | return mktime(&t); 116 | } 117 | -------------------------------------------------------------------------------- /nodelib/base/Date_Time.h: -------------------------------------------------------------------------------- 1 | /* 2 | * DateTime.h 3 | * 4 | * Created on: Jan 12,2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef DATE_TIME_H_ 9 | #define DATE_TIME_H_ 10 | 11 | #include "Time_Value.h" 12 | 13 | class Date_Time { 14 | public: 15 | Date_Time(void); 16 | 17 | explicit Date_Time(const Time_Value &timevalue); 18 | 19 | Date_Time(long day, 20 | long month = 0, 21 | long year = 0, 22 | long hour = 0, 23 | long minute = 0, 24 | long second = 0, 25 | long microsec = 0, 26 | long wday = 0); 27 | 28 | /// Update to the current time/date. 29 | void update(void); 30 | 31 | /// Update to the given Time_Value 32 | void update(const Time_Value &timevalue); 33 | 34 | long day(void) const; 35 | void day(long day); 36 | 37 | long month(void) const; 38 | void month(long month); 39 | 40 | long year(void) const; 41 | void year(long year); 42 | 43 | long hour(void) const; 44 | void hour(long hour); 45 | 46 | long minute(void) const; 47 | void minute(long minute); 48 | 49 | long second(void) const; 50 | void second(long second); 51 | 52 | long microsec(void) const; 53 | void microsec(long microsec); 54 | 55 | long weekday(void) const; 56 | void weekday(long wday); 57 | 58 | time_t time_sec(void); 59 | 60 | private: 61 | long day_; 62 | long month_; 63 | long year_; 64 | long hour_; 65 | long minute_; 66 | long second_; 67 | long microsec_; 68 | long wday_; 69 | }; 70 | 71 | #endif /* DATE_TIME_H_ */ 72 | -------------------------------------------------------------------------------- /nodelib/base/List.h: -------------------------------------------------------------------------------- 1 | /* 2 | * List.h 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef LIST_H_ 9 | #define LIST_H_ 10 | 11 | #include 12 | #include "Thread_Guard.h" 13 | 14 | template 15 | class List { 16 | public: 17 | typedef std::list TList; 18 | typedef typename TList::const_iterator const_iterator; 19 | 20 | List(void); 21 | ~List(void); 22 | 23 | void push_back(const Obj &v); 24 | Obj &front(); 25 | Obj pop_front(); 26 | 27 | bool empty(); 28 | void clear(); 29 | size_t size() const; 30 | size_t size(); 31 | 32 | const_iterator begin() const; 33 | const_iterator end() const; 34 | 35 | const std::list &get_list(); 36 | const std::list &get_list() const; 37 | 38 | private: 39 | TList list_; 40 | size_t size_; 41 | LOCK lock_; 42 | }; 43 | 44 | //////////////////////////////////////////////////////////////////////////////// 45 | 46 | template 47 | List::List(void) : size_(0) { } 48 | 49 | template 50 | List::~List(void) { } 51 | 52 | template 53 | void List::push_back(const Obj &v) { 54 | GUARD(LOCK, mon, this->lock_); 55 | ++size_; 56 | list_.push_back(v); 57 | return ; 58 | } 59 | 60 | template 61 | Obj &List::front() { 62 | GUARD(LOCK, mon, this->lock_); 63 | return list_.front(); 64 | } 65 | 66 | template 67 | Obj List::pop_front() { 68 | GUARD(LOCK, mon, this->lock_); 69 | Obj val = list_.front(); 70 | --size_; 71 | list_.pop_front(); 72 | return val; 73 | } 74 | 75 | template 76 | bool List::empty() { 77 | GUARD(LOCK, mon, this->lock_); 78 | return list_.empty(); 79 | } 80 | 81 | template 82 | void List::clear() { 83 | GUARD(LOCK, mon, this->lock_); 84 | size_ = 0; 85 | list_.clear(); 86 | return ; 87 | } 88 | 89 | template 90 | size_t List::size() const { 91 | GUARD(LOCK, mon, this->lock_); 92 | return size_; 93 | } 94 | 95 | template 96 | size_t List::size() { 97 | GUARD(LOCK, mon, this->lock_); 98 | return size_; 99 | } 100 | 101 | template 102 | const std::list &List::get_list() { 103 | GUARD(LOCK, mon, this->lock_); 104 | return list_; 105 | } 106 | 107 | template 108 | const std::list &List::get_list() const { 109 | GUARD(LOCK, mon, this->lock_); 110 | return list_; 111 | } 112 | 113 | template 114 | typename List::const_iterator List::begin() const { 115 | return list_.begin(); 116 | } 117 | 118 | template 119 | typename List::const_iterator List::end() const { 120 | return list_.end(); 121 | } 122 | 123 | #endif /* LIST_H_ */ 124 | -------------------------------------------------------------------------------- /nodelib/base/Log.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/nodelib/base/Log.cpp -------------------------------------------------------------------------------- /nodelib/base/Log.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Log.h 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | * 7 | */ 8 | 9 | #ifndef LOG_H_ 10 | #define LOG_H_ 11 | 12 | #include 13 | #include 14 | #include "List.h" 15 | #include "Thread.h" 16 | #include "Thread_Guard.h" 17 | #include "Time_Value.h" 18 | 19 | struct LOG_File_Info { 20 | LOG_File_Info(void): tv(Time_Value::zero), fp(0) { } 21 | 22 | Time_Value tv; 23 | std::string filepath; 24 | FILE *fp; 25 | }; 26 | 27 | class Log: public Thread { 28 | typedef Mutex_Lock Log_File_Lock; 29 | typedef List String_List; 30 | public: 31 | static int msg_buf_size; 32 | static int backtrace_size; 33 | static std::string msg_head[]; 34 | 35 | static Log *instance(void); 36 | static void destroy(void); 37 | 38 | virtual void run_handler(void); 39 | virtual int process_list(void); 40 | 41 | void log_debug(const char *fmt, ...); 42 | void log_info(const char *fmt, ...); 43 | void log_warn(const char *fmt, ...); 44 | void log_error(const char *fmt, ...); 45 | void log_trace(const char *fmt, ...); 46 | void log_fatal(const char *fmt, ...); 47 | 48 | inline void set_log_file(bool log_file) { log_file_ = log_file; } 49 | inline void set_log_level(int log_level) { log_level_ = log_level; } 50 | inline void set_folder_name(std::string &folder_name) { folder_name_ = folder_name; } 51 | inline void push_log(std::string log_str) { 52 | notify_lock_.lock(); 53 | log_list_.push_back(log_str); 54 | notify_lock_.signal(); 55 | notify_lock_.unlock(); 56 | } 57 | 58 | private: 59 | Log(void); 60 | virtual ~Log(void); 61 | 62 | void assembly_msg(int log_flag, const char *fmt, va_list ap); 63 | void make_log_dir(void); 64 | void make_log_filepath(std::string &path); 65 | void log_file(std::string &log_str); 66 | private: 67 | static Log *instance_; 68 | String_List log_list_; //要写入文件的日志列表 69 | 70 | bool log_file_; //是否写入文件 71 | int log_level_; //日志级别,小于该级别的日志类型不会记录 72 | std::string log_dir_; 73 | std::string folder_name_; 74 | Log_File_Lock file_lock_; 75 | LOG_File_Info file_info_; 76 | }; 77 | 78 | #define LOG_INSTACNE Log::instance() 79 | 80 | //打印程序调试信息 81 | #define LOG_DEBUG(FMT, ...) do { \ 82 | LOG_INSTACNE->log_debug("in %s:%d function %s: "#FMT, __FILE__, __LINE__, __func__, ##__VA_ARGS__); \ 83 | } while (0) 84 | 85 | //打印程序运行信息 86 | #define LOG_INFO(FMT, ...) do { \ 87 | LOG_INSTACNE->log_info("in %s:%d function %s: "#FMT, __FILE__, __LINE__, __func__, ##__VA_ARGS__); \ 88 | } while (0) 89 | 90 | //打印程序警告信息 91 | #define LOG_WARN(FMT, ...) do { \ 92 | LOG_INSTACNE->log_warn("in %s:%d function %s: "#FMT, __FILE__, __LINE__, __func__, ##__VA_ARGS__); \ 93 | } while (0) 94 | 95 | //打印程序错误信息 96 | #define LOG_ERROR(FMT, ...) do { \ 97 | LOG_INSTACNE->log_error("in %s:%d function %s: "#FMT, __FILE__, __LINE__, __func__, ##__VA_ARGS__); \ 98 | } while (0) 99 | 100 | //打印程序运行堆栈 101 | #define LOG_TRACE(FMT, ...) do { \ 102 | LOG_INSTACNE->log_trace("in %s:%d function %s: "#FMT, __FILE__, __LINE__, __func__, ##__VA_ARGS__); \ 103 | } while (0) 104 | 105 | //打印程序崩溃信息,将会导致应用程序的退出 106 | #define LOG_FATAL(FMT, ...) do { \ 107 | LOG_INSTACNE->log_fatal("in %s:%d function %s: "#FMT, __FILE__, __LINE__, __func__, ##__VA_ARGS__); \ 108 | } while (0) 109 | 110 | #endif /* LOG_H_ */ 111 | -------------------------------------------------------------------------------- /nodelib/base/Priority_Queue.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Priority_Queue.h 3 | * 4 | * Created on: Mar 22,2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef PRIORITY_QUEUE_H_ 9 | #define PRIORITY_QUEUE_H_ 10 | 11 | #include "Thread_Guard.h" 12 | 13 | //优先队列 14 | template 15 | class Priority_Queue { 16 | public: 17 | typedef std::vector Container; 18 | 19 | Obj top(){ 20 | GUARD(LOCK, mon, this->lock_); 21 | return container_.front(); 22 | } 23 | void push(Obj obj){ 24 | GUARD(LOCK, mon, this->lock_); 25 | container_.push_back(obj); 26 | std::push_heap(container_.begin(), container_.end(), Compare()); 27 | } 28 | void pop(){ 29 | GUARD(LOCK, mon, this->lock_); 30 | std::pop_heap(container_.begin(), container_.end(), Compare()); 31 | container_.pop_back(); 32 | } 33 | bool empty(){ 34 | GUARD(LOCK, mon, this->lock_); 35 | return container_.empty(); 36 | } 37 | private: 38 | Container container_; 39 | LOCK lock_; 40 | }; 41 | 42 | #endif /* PRIORITY_QUEUE_H_ */ 43 | -------------------------------------------------------------------------------- /nodelib/base/Proc_Info.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/nodelib/base/Proc_Info.cpp -------------------------------------------------------------------------------- /nodelib/base/Proc_Info.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/nodelib/base/Proc_Info.h -------------------------------------------------------------------------------- /nodelib/base/Sha1.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Sha1.h 3 | * 4 | * Copyright (C) 1998, 2009 5 | * Paul E. Jones 6 | * All Rights Reserved. 7 | * 8 | ***************************************************************************** 9 | * $Id: sha1.h 12 2009-06-22 19:34:25Z paulej $ 10 | ***************************************************************************** 11 | * 12 | * Description: 13 | * This class implements the Secure Hashing Standard as defined 14 | * in FIPS PUB 180-1 published April 17, 1995. 15 | * 16 | * Many of the variable names in this class, especially the single 17 | * character names, were used because those were the names used 18 | * in the publication. 19 | * 20 | * Please read the file sha1.cpp for more information. 21 | */ 22 | 23 | #ifndef _SHA1_H_ 24 | #define _SHA1_H_ 25 | 26 | class SHA1 27 | { 28 | public: 29 | SHA1(); 30 | virtual ~SHA1(); 31 | 32 | /* 33 | * Re-initialize the class 34 | */ 35 | void Reset(); 36 | 37 | /* 38 | * Returns the message digest 39 | */ 40 | bool Result(unsigned *message_digest_array); 41 | 42 | /* 43 | * Provide input to SHA1 44 | */ 45 | void Input( const unsigned char *message_array, 46 | unsigned length); 47 | void Input( const char *message_array, 48 | unsigned length); 49 | void Input(unsigned char message_element); 50 | void Input(char message_element); 51 | SHA1& operator<<(const char *message_array); 52 | SHA1& operator<<(const unsigned char *message_array); 53 | SHA1& operator<<(const char message_element); 54 | SHA1& operator<<(const unsigned char message_element); 55 | 56 | private: 57 | /* 58 | * Process the next 512 bits of the message 59 | */ 60 | void ProcessMessageBlock(); 61 | 62 | /* 63 | * Pads the current message block to 512 bits 64 | */ 65 | void PadMessage(); 66 | 67 | /* 68 | * Performs a circular left shift operation 69 | */ 70 | inline unsigned CircularShift(int bits, unsigned word); 71 | 72 | unsigned H[5]; // Message digest buffers 73 | 74 | unsigned Length_Low; // Message length in bits 75 | unsigned Length_High; // Message length in bits 76 | 77 | unsigned char Message_Block[64]; // 512-bit message blocks 78 | int Message_Block_Index; // Index into message block array 79 | 80 | bool Computed; // Is the digest computed? 81 | bool Corrupted; // Is the message digest corruped? 82 | }; 83 | 84 | #endif // _SHA1_H_ 85 | -------------------------------------------------------------------------------- /nodelib/base/Thread.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Thread.h 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef THREAD_H_ 9 | #define THREAD_H_ 10 | 11 | #include 12 | #include "Thread_Lock.h" 13 | 14 | class Thread { 15 | public: 16 | Thread(void) : tid(0) { } 17 | virtual ~Thread(void) { } 18 | 19 | static void *create_func(void *arg) { 20 | Thread *self = (Thread *)arg; 21 | pthread_cleanup_push(cleanup_func, arg); 22 | self->run_handler(); 23 | pthread_cleanup_pop(1); 24 | return self; 25 | } 26 | 27 | static void cleanup_func(void *arg) { 28 | Thread *self = (Thread *)arg; 29 | self->exit_handler(); 30 | return ; 31 | } 32 | 33 | virtual void run_handler(void) { } 34 | 35 | virtual void exit_handler(void) { } 36 | 37 | int thr_create(void) { 38 | return ::pthread_create(&tid, NULL, create_func, this); 39 | } 40 | 41 | int thr_cancel(void) { 42 | return ::pthread_cancel(tid); 43 | } 44 | 45 | int thr_join(void) { 46 | return ::pthread_join(tid, NULL); 47 | } 48 | 49 | int thr_cancel_join(void) { 50 | int ret; 51 | if ((ret = thr_cancel()) == 0) { 52 | ret = thr_join(); 53 | } else { 54 | return -1; 55 | } 56 | return ret; 57 | } 58 | 59 | void thr_exit(void *rval_ptr) { 60 | ::pthread_exit(rval_ptr); 61 | } 62 | 63 | pthread_t thread_id() { 64 | return tid; 65 | } 66 | 67 | protected: 68 | Notify_Lock notify_lock_; //条件变量通知锁 69 | 70 | private: 71 | pthread_t tid; 72 | }; 73 | 74 | #endif /* THREAD_H_ */ 75 | -------------------------------------------------------------------------------- /nodelib/base/Thread_Guard.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Thread_Guard.h 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef THREAD_GUARD_H_ 9 | #define THREAD_GUARD_H_ 10 | 11 | #include "Thread_Lock.h" 12 | 13 | template 14 | class Mutex_Guard { 15 | public: 16 | Mutex_Guard(LOCK &l); 17 | virtual ~Mutex_Guard(); 18 | 19 | int acquire(void); 20 | int release(void); 21 | 22 | int acquire_read(void); 23 | int acquire_write(void); 24 | 25 | private: 26 | LOCK *lock_; 27 | }; 28 | 29 | //////////////////////////////////////////////////////////////// 30 | template 31 | class Read_Guard { 32 | public: 33 | Read_Guard(LOCK &l); 34 | virtual ~Read_Guard(); 35 | 36 | int release(void); 37 | int acquire_read(void); 38 | 39 | private: 40 | LOCK *lock_; 41 | }; 42 | 43 | template 44 | Read_Guard::Read_Guard(LOCK &l) : lock_(&l) { 45 | acquire_read(); 46 | } 47 | 48 | template 49 | Read_Guard::~Read_Guard(void) { this->release(); } 50 | 51 | template 52 | int Read_Guard::release(void) { return lock_->release(); } 53 | 54 | template 55 | int Read_Guard::acquire_read(void) { return lock_->acquire_read(); } 56 | 57 | template 58 | class Write_Guard { 59 | public: 60 | Write_Guard(LOCK &l); 61 | virtual ~Write_Guard(); 62 | 63 | int release(void); 64 | int acquire_write(void); 65 | 66 | private: 67 | LOCK *lock_; 68 | }; 69 | 70 | template 71 | Write_Guard::Write_Guard(LOCK &l) : lock_(&l) { 72 | acquire_write(); 73 | } 74 | 75 | template 76 | Write_Guard::~Write_Guard(void) { this->release(); } 77 | 78 | template 79 | int Write_Guard::release(void) { return lock_->release(); } 80 | 81 | template 82 | int Write_Guard::acquire_write(void) { return lock_->acquire_write(); } 83 | 84 | //////////////////////////////////////////////////////////////// 85 | template 86 | Mutex_Guard::Mutex_Guard(LOCK &l) : lock_(&l) { 87 | //lock_ = &l; 88 | this->acquire(); 89 | } 90 | 91 | template 92 | Mutex_Guard::~Mutex_Guard(void) { 93 | this->release(); 94 | } 95 | 96 | template 97 | int Mutex_Guard::acquire(void) { 98 | return lock_->acquire(); 99 | } 100 | 101 | template 102 | int Mutex_Guard::release(void) { 103 | return lock_->release(); 104 | } 105 | 106 | template 107 | int Mutex_Guard::acquire_read(void) { 108 | return lock_->acquire_read(); 109 | } 110 | 111 | template 112 | int Mutex_Guard::acquire_write(void) { 113 | return lock_->acquire_write(); 114 | } 115 | 116 | //////////////////////////////////////////////////////////////// 117 | #define GUARD(MUTEX_LOCK, OBJ, LOCK) Mutex_Guard< MUTEX_LOCK > OBJ(LOCK); 118 | #define GUARD_READ(MUTEX_LOCK, OBJ, LOCK) Read_Guard< MUTEX_LOCK > OBJ(LOCK); 119 | #define GUARD_WRITE(MUTEX_LOCK, OBJ, LOCK) Write_Guard< MUTEX_LOCK > OBJ(LOCK); 120 | 121 | #endif /* THREAD_GUARD_H_ */ 122 | -------------------------------------------------------------------------------- /nodelib/base/Time_Value.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Time_Value.cpp 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include 9 | #include "Byte_Buffer.h" 10 | #include "Date_Time.h" 11 | #include "Time_Value.h" 12 | 13 | const Time_Value Time_Value::zero; 14 | const Time_Value Time_Value::max(LONG_MAX, 0); 15 | 16 | Time_Value Time_Value::gettimeofday(void) { 17 | timeval now_t; 18 | ::gettimeofday(&now_t, NULL); 19 | Time_Value now_tv(now_t); 20 | 21 | return now_tv; 22 | } 23 | 24 | int Time_Value::sleep(const Time_Value &tv) { 25 | timespec ts = tv; 26 | return ::nanosleep (&ts, 0); 27 | } 28 | 29 | Time_Value::Time_Value(long sec, long usec) { 30 | set(sec, usec); 31 | } 32 | 33 | Time_Value::Time_Value(const struct timeval &t) { 34 | set(t); 35 | } 36 | 37 | Time_Value::Time_Value(const Time_Value &tv) { 38 | set(tv); 39 | } 40 | 41 | void Time_Value::debug_dump(void) const { 42 | /* char str[512]; 43 | memset(str, 0, sizeof(str)); 44 | snprintf(str, sizeof(str), "sec = [%d], usec = [%d]", (int)this->tv_.tv_sec, (int)this->tv_.tv_usec); 45 | std::cerr << str;*/ 46 | } 47 | 48 | void Time_Value::debug_dump(char *str, size_t *sl) { 49 | memset(str, 0, *sl); 50 | snprintf(str, *sl, "%d-%d", (int)this->tv_.tv_sec, (int)this->tv_.tv_usec); 51 | } 52 | 53 | void Time_Value::normalize(void) { 54 | if (this->tv_.tv_usec >= ONE_SECOND_IN_USECS) { 55 | do { 56 | ++this->tv_.tv_sec; 57 | this->tv_.tv_usec -= ONE_SECOND_IN_USECS; 58 | } while (this->tv_.tv_usec >= ONE_SECOND_IN_USECS); 59 | } else if (this->tv_.tv_usec <= -ONE_SECOND_IN_USECS) { 60 | do { 61 | --this->tv_.tv_sec; 62 | this->tv_.tv_usec += ONE_SECOND_IN_USECS; 63 | } while (this->tv_.tv_usec <= -ONE_SECOND_IN_USECS); 64 | } 65 | 66 | if (this->tv_.tv_sec >= 1 && this->tv_.tv_usec < 0) { 67 | --this->tv_.tv_sec; 68 | this->tv_.tv_usec += ONE_SECOND_IN_USECS; 69 | } 70 | } 71 | 72 | bool operator > (const Time_Value &tv1, const Time_Value &tv2) { 73 | if (tv1.sec() > tv2.sec()) 74 | return 1; 75 | else if (tv1.sec() == tv2.sec() && tv1.usec() > tv2.usec()) 76 | return 1; 77 | else 78 | return 0; 79 | } 80 | 81 | bool operator < (const Time_Value &tv1, const Time_Value &tv2) { 82 | return tv2 > tv1; 83 | } 84 | 85 | bool operator >= (const Time_Value &tv1, const Time_Value &tv2) { 86 | if (tv1.sec() > tv2.sec()) 87 | return 1; 88 | else if (tv1.sec() == tv2.sec() && tv1.usec() >= tv2.usec()) 89 | return 1; 90 | else 91 | return 0; 92 | } 93 | 94 | bool operator <= (const Time_Value &tv1, const Time_Value &tv2) { 95 | return tv2 >= tv1; 96 | } 97 | 98 | Time_Value operator - (const Time_Value &tv1, const Time_Value &tv2) { 99 | Time_Value delta(tv1); 100 | delta -= tv2; 101 | 102 | return delta; 103 | } 104 | 105 | Time_Value operator + (const Time_Value &tv1, const Time_Value &tv2) { 106 | Time_Value sum (tv1); 107 | sum += tv2; 108 | 109 | return sum; 110 | } 111 | 112 | Time_Value &Time_Value::operator -= (const Time_Value &tv) { 113 | this->sec (this->sec () - tv.sec ()); 114 | this->usec (this->usec () - tv.usec ()); 115 | this->normalize (); 116 | return *this; 117 | } 118 | 119 | Time_Value &Time_Value::operator += (const Time_Value &tv) { 120 | this->sec (this->sec () + tv.sec ()); 121 | this->usec (this->usec () + tv.usec ()); 122 | this->normalize (); 123 | return *this; 124 | } 125 | 126 | bool operator == (const Time_Value &tv1, const Time_Value &tv2) { 127 | return tv1.sec() == tv2.sec() && tv1.usec() == tv2.usec(); 128 | } 129 | 130 | bool operator != (const Time_Value &tv1, const Time_Value &tv2) { 131 | return !(tv1 == tv2); 132 | } 133 | 134 | Time_Value::operator timespec() const { 135 | timespec tv; 136 | tv.tv_sec = this->sec (); 137 | tv.tv_nsec = this->tv_.tv_usec * 1000; 138 | return tv; 139 | } 140 | 141 | int Time_Value::serialize(Byte_Buffer &buffer) const { 142 | buffer.write_int64(tv_.tv_sec); 143 | buffer.write_int64(tv_.tv_usec); 144 | return 0; 145 | } 146 | 147 | int Time_Value::deserialize(Byte_Buffer &buffer) { 148 | buffer.read_int64(tv_.tv_sec); 149 | buffer.read_int64(tv_.tv_usec); 150 | return 0; 151 | } 152 | -------------------------------------------------------------------------------- /nodelib/db/DB_Operator.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Mongo_Operator.h 3 | * 4 | * Created on: Dec 18, 2016 5 | * Author: lijunliang 6 | */ 7 | 8 | #ifndef DB_OPERATOR_H_ 9 | #define DB_OPERATOR_H_ 10 | 11 | #include "DB_Struct.h" 12 | 13 | class DB_Operator { 14 | public: 15 | DB_Operator(void) {}; 16 | virtual ~DB_Operator(void) {}; 17 | 18 | virtual bool connect_to_db(int db_id, std::string &ip, int port, std::string &user, std::string &password, std::string &pool_name) { return false; } 19 | 20 | //根据条件查询db数据 21 | virtual int select_db_data(int db_id, DB_Struct *db_struct, std::string &condition_name, std::string &condition_value, std::string &query_name, std::string &query_type, Bit_Buffer &buffer) { return 0;} 22 | //数据库加载数据到内存buffer,保存数据通过内存buffer操作 23 | virtual int load_data(int db_id, DB_Struct *db_struct, int64_t key_index, std::vector &buffer_vec) { return 0; } 24 | virtual int save_data(int db_id, DB_Struct *db_struct, Bit_Buffer &buffer) { return 0; } 25 | virtual int delete_data(int db_id, DB_Struct *db_struct, int64_t key_index) { return 0; } 26 | 27 | protected: 28 | MUTEX_LOCK connection_map_lock_; 29 | }; 30 | 31 | #endif /* DB_OPERATOR_H_ */ 32 | -------------------------------------------------------------------------------- /nodelib/db/Mongo_Operator.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Mongo_Operator.h 3 | * 4 | * Created on: Dec 29, 2015 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef MOMGO_OPERATOR_H_ 9 | #define MONGO_OPERATOR_H_ 10 | 11 | #ifdef MONGO_DB_IMPLEMENT 12 | 13 | #include "mongo/client/dbclient.h" 14 | #include 15 | #include "Object_Pool.h" 16 | #include "DB_Operator.h" 17 | 18 | using namespace mongo; 19 | 20 | class Mongo_Operator : public DB_Operator { 21 | public: 22 | typedef std::unordered_map Connection_Map; 23 | //typedef std::unordered_map DB_Connection_Map; 24 | typedef Object_Pool Connection_Pool; 25 | 26 | Mongo_Operator(void); 27 | virtual ~Mongo_Operator(void); 28 | 29 | virtual bool connect_to_db(int db_id, std::string &ip, int port, std::string &user, std::string &password, std::string &pool_name); 30 | 31 | //根据条件查询db数据 32 | virtual int select_db_data(int db_id, DB_Struct *db_struct, std::string &condition_name, std::string &condition_value, std::string &query_name, std::string &query_type, Bit_Buffer &buffer); 33 | //数据库加载数据到内存buffer,保存数据通过内存buffer操作 34 | virtual int load_data(int db_id, DB_Struct *db_struct, int64_t key_index, std::vector &buffer_vec); 35 | virtual int save_data(int db_id, DB_Struct *db_struct, Bit_Buffer &buffer); 36 | virtual int delete_data(int db_id, DB_Struct *db_struct, int64_t key_index); 37 | 38 | private: 39 | mongo::DBClientConnection &get_connection(int db_id); 40 | 41 | //数据输入:bsonobj 数据输出:buffer 42 | int load_data_single(DB_Struct *db_struct, BSONObj &bsonobj, Bit_Buffer &buffer); 43 | int load_data_arg(DB_Struct *db_struct, const Field_Info &field_info, BSONObj &bsonobj, Bit_Buffer &buffer); 44 | int load_data_vector(DB_Struct *db_struct, const Field_Info &field_info, BSONObj &bsonobj, Bit_Buffer &buffer); 45 | int load_data_map(DB_Struct *db_struct, const Field_Info &field_info, BSONObj &bsonobj, Bit_Buffer &buffer); 46 | int load_data_struct(DB_Struct *db_struct, const Field_Info &field_info, BSONObj &bsonobj, Bit_Buffer &buffer); 47 | 48 | //数据输入:buffer 数据输出:builder 49 | int save_data_arg(DB_Struct *db_struct, const Field_Info &field_info, BSONObjBuilder &builder, Bit_Buffer &buffer); 50 | int save_data_vector(DB_Struct *db_struct, const Field_Info &field_info, BSONObjBuilder &builder, Bit_Buffer &buffer); 51 | int save_data_map(DB_Struct *db_struct, const Field_Info &field_info, BSONObjBuilder &builder, Bit_Buffer &buffer); 52 | int save_data_struct(DB_Struct *db_struct, const Field_Info &field_info, BSONObjBuilder &builder, Bit_Buffer &buffer); 53 | 54 | private: 55 | Connection_Pool connection_pool_; 56 | Connection_Map connection_map_; 57 | }; 58 | 59 | #endif 60 | 61 | #endif /* MONGO_OPERATOR_H_ */ 62 | -------------------------------------------------------------------------------- /nodelib/db/Mysql_Conn.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Mysql_Conn.h 3 | * 4 | * Created on: Jan 4,2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef MYSQL_CONN_H_ 9 | #define MYSQL_CONN_H_ 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include "Thread_Lock.h" 22 | 23 | class DataBuf : public std::streambuf 24 | { 25 | public: 26 | DataBuf(char* buf, size_t len) { 27 | setg(buf, buf, buf+len); 28 | } 29 | }; 30 | 31 | class Mysql_Pool; 32 | class Mysql_Conn { 33 | public: 34 | Mysql_Conn(Mysql_Pool* mysql_pool); 35 | virtual ~Mysql_Conn(); 36 | 37 | int init(void); 38 | sql::PreparedStatement* create_pstmt(const char* str_sql); 39 | std::string& get_pool_name(); 40 | 41 | sql::ResultSet* execute_query(const char* str_sql); 42 | int execute_update(const char* str_sql); 43 | int execute(const char* str_sql); 44 | 45 | private: 46 | Mysql_Pool* mysql_pool_; 47 | sql::Connection* conn_; 48 | sql::Statement* stmt_ ; 49 | }; 50 | 51 | class Mysql_Pool { 52 | public: 53 | Mysql_Pool(std::string& pool_name, std::string& server_ip, uint32_t server_port, 54 | std::string& username, std::string& password, int32_t max_conn_cnt); 55 | virtual ~Mysql_Pool(); 56 | 57 | int init(void); 58 | Mysql_Conn* get_mysql_conn(); 59 | void rel_mysql_conn(Mysql_Conn* conn); 60 | 61 | inline std::string& get_pool_name() { return pool_name_; } 62 | inline std::string& get_server_ip() { return server_ip_; } 63 | inline int32_t get_server_port() { return server_port_; } 64 | inline std::string& get_username() { return username_; } 65 | inline std::string& get_passwrod() { return password_; } 66 | inline sql::Driver* get_driver(){return driver_;} 67 | 68 | private: 69 | std::string pool_name_; 70 | std::string server_ip_; 71 | int32_t server_port_; 72 | std::string username_; 73 | std::string password_; 74 | int32_t cur_conn_cnt_; 75 | int32_t max_conn_cnt_; 76 | 77 | sql::Driver* driver_; 78 | std::list free_list_; 79 | Notify_Lock notify_lock_; 80 | }; 81 | 82 | class Mysql_Manager { 83 | public: 84 | static Mysql_Manager* instance(); 85 | int init(std::string& server_ip, int server_port, std::string& username, std::string& password, std::string& pool_name, int max_conn_cnt); 86 | 87 | Mysql_Conn* get_mysql_conn(std::string& pool_name); 88 | void rel_mysql_conn(Mysql_Conn* conn); 89 | 90 | private: 91 | Mysql_Manager(); 92 | virtual ~Mysql_Manager(); 93 | 94 | private: 95 | static Mysql_Manager* instance_; 96 | std::unordered_map mysql_pool_map_; 97 | }; 98 | 99 | #define MYSQL_MANAGER Mysql_Manager::instance() 100 | 101 | #endif /* MYSQL_CONN_H_ */ 102 | -------------------------------------------------------------------------------- /nodelib/db/Mysql_Operator.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Mysql_Operator.h 3 | * 4 | * Created on: Jul 20, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef MYSQL_OPERATOR_H_ 9 | #define MYSQL_OPERATOR_H_ 10 | 11 | #include 12 | #include "Mysql_Conn.h" 13 | #include "DB_Operator.h" 14 | 15 | class Mysql_Operator : public DB_Operator { 16 | public: 17 | typedef std::unordered_map Connection_Map; 18 | //typedef std::unordered_map DB_Connection_Map; 19 | 20 | Mysql_Operator(void); 21 | virtual ~Mysql_Operator(void); 22 | 23 | virtual bool connect_to_db(int db_id, std::string &ip, int port, std::string &user, std::string &password, std::string &pool_name); 24 | 25 | //根据条件查询db数据 26 | virtual int select_db_data(int db_id, DB_Struct *db_struct, std::string &condition_name, std::string &condition_value, std::string &query_name, std::string &query_type, Bit_Buffer &buffer); 27 | //数据库加载数据到内存buffer,保存数据通过内存buffer操作 28 | virtual int load_data(int db_id, DB_Struct *db_struct, int64_t key_index, std::vector &buffer_vec); 29 | virtual int save_data(int db_id, DB_Struct *db_struct, Bit_Buffer &buffer); 30 | virtual int delete_data(int db_id, DB_Struct *db_struct, int64_t key_index); 31 | 32 | private: 33 | Mysql_Conn *get_connection(int db_id); 34 | 35 | int load_data_single(DB_Struct *db_struct, sql::ResultSet *result, Bit_Buffer &buffer); 36 | int load_data_arg(DB_Struct *db_struct, const Field_Info &field_info, sql::ResultSet *result, Bit_Buffer &buffer); 37 | int load_data_vector(DB_Struct *db_struct, const Field_Info &field_info, sql::ResultSet *result, Bit_Buffer &buffer); 38 | int load_data_map(DB_Struct *db_struct, const Field_Info &field_info, sql::ResultSet *result, Bit_Buffer &buffer); 39 | int load_data_struct(DB_Struct *db_struct, const Field_Info &field_info, sql::ResultSet *result, Bit_Buffer &buffer); 40 | 41 | //根据byte_buffer生成bit_buffer 42 | int build_bit_buffer_arg(DB_Struct *db_struct, const Field_Info &field_info, Bit_Buffer &bit_buffer, Byte_Buffer &byte_buffer); 43 | int build_bit_buffer_vector(DB_Struct *db_struct, const Field_Info &field_info, Bit_Buffer &bit_buffer, Byte_Buffer &byte_buffer); 44 | int build_bit_buffer_map(DB_Struct *db_struct, const Field_Info &field_info, Bit_Buffer &bit_buffer, Byte_Buffer &byte_buffer); 45 | int build_bit_buffer_struct(DB_Struct *db_struct, const Field_Info &field_info, Bit_Buffer &bit_buffer, Byte_Buffer &byte_buffer); 46 | 47 | //根据bit_buffer生成byte_buffer 48 | int build_byte_buffer_arg(DB_Struct *db_struct, const Field_Info &field_info, Bit_Buffer &bit_buffer, Byte_Buffer &byte_buffer); 49 | int build_byte_buffer_vector(DB_Struct *db_struct, const Field_Info &field_info, Bit_Buffer &bit_buffer, Byte_Buffer &byte_buffer); 50 | int build_byte_buffer_map(DB_Struct *db_struct, const Field_Info &field_info, Bit_Buffer &bit_buffer, Byte_Buffer &byte_buffer); 51 | int build_byte_buffer_struct(DB_Struct *db_struct, const Field_Info &field_info, Bit_Buffer &bit_buffer, Byte_Buffer &byte_buffer); 52 | 53 | private: 54 | Connection_Map connection_map_; 55 | }; 56 | 57 | #endif /* MYSQL_OPERATOR_H_ */ 58 | -------------------------------------------------------------------------------- /nodelib/network/Accept.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/nodelib/network/Accept.cpp -------------------------------------------------------------------------------- /nodelib/network/Accept.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Accept.h 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef ACCEPT_H_ 9 | #define ACCEPT_H_ 10 | 11 | #include "Thread.h" 12 | 13 | class Endpoint; 14 | class Accept: public Thread { 15 | public: 16 | Accept(void); 17 | virtual ~Accept(void); 18 | 19 | int init(Endpoint *endpoint, int port); 20 | int fini(void); 21 | 22 | void server_listen(void); 23 | void server_accept(void); 24 | virtual int accept_svc(int connfd); 25 | 26 | virtual void run_handler(void); 27 | virtual void exit_handler(void); 28 | 29 | protected: 30 | Endpoint *endpoint_; 31 | 32 | private: 33 | int port_; 34 | int listenfd_; 35 | }; 36 | 37 | #endif /* ACCEPT_H_ */ 38 | -------------------------------------------------------------------------------- /nodelib/network/Connect.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Connect.cpp 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include "Base_Function.h" 12 | #include "Endpoint.h" 13 | #include "Connect.h" 14 | 15 | Connect::Connect(void) : endpoint_(0) { } 16 | 17 | Connect::~Connect(void) { } 18 | 19 | int Connect::init(Endpoint *endpoint) { 20 | endpoint_ = endpoint; 21 | return 0; 22 | } 23 | 24 | int Connect::connect(const char *ip, int port) { 25 | int connfd = 0; 26 | struct sockaddr_in serveraddr; 27 | 28 | if ((connfd = ::socket(AF_INET, SOCK_STREAM, 0)) == -1) { 29 | LOG_FATAL("connect socket fail, connfd = %d", connfd); 30 | } 31 | 32 | memset(&serveraddr, 0, sizeof(serveraddr)); 33 | serveraddr.sin_family = AF_INET; 34 | serveraddr.sin_port = htons(port); 35 | 36 | if (::inet_pton(AF_INET, ip, &serveraddr.sin_addr) <= 0) { 37 | LOG_ERROR("connect inet_pton fail, ip = %s, port = %d", ip, port); 38 | ::close(connfd); 39 | return -1; 40 | } 41 | 42 | if (::connect(connfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) { 43 | ::close(connfd); 44 | return -1; 45 | } 46 | 47 | set_nonblock(connfd); 48 | return connect_svc(connfd); 49 | } 50 | 51 | int Connect::connect_svc(int connfd) { 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /nodelib/network/Connect.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Connect.h 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef CONNECT_H_ 9 | #define CONNECT_H_ 10 | 11 | class Endpoint; 12 | class Connect { 13 | public: 14 | Connect(void); 15 | virtual ~Connect(void); 16 | 17 | int init(Endpoint *endpoint); 18 | int connect(const char *ip, int port); 19 | virtual int connect_svc(int connfd); 20 | 21 | protected: 22 | Endpoint *endpoint_; 23 | }; 24 | 25 | #endif /* CONNECT_H_ */ 26 | -------------------------------------------------------------------------------- /nodelib/network/Endpoint.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Endpoint.h 3 | * 4 | * Created on: Sep 22, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef ENDPOINT_H_ 9 | #define ENDPOINT_H_ 10 | 11 | #include "Buffer_Pool_Group.h" 12 | #include "Object_Pool.h" 13 | #include "Accept.h" 14 | #include "Connect.h" 15 | #include "Network.h" 16 | #include "Svc.h" 17 | #include "Svc_Static_List.h" 18 | 19 | class Endpoint_Accept: public Accept { 20 | public: 21 | virtual int accept_svc(int connfd); 22 | }; 23 | 24 | class Endpoint_Connect: public Connect { 25 | public: 26 | virtual int connect_svc(int connfd); 27 | }; 28 | 29 | class Endpoint_Network: public Network { 30 | public: 31 | virtual int drop_handler(int cid); 32 | virtual Svc *find_svc(int cid); 33 | }; 34 | 35 | class Endpoint_Svc: public Svc { 36 | public: 37 | virtual Byte_Buffer *pop_buffer(int cid); 38 | virtual int push_buffer(int cid, Byte_Buffer *buffer); 39 | virtual int post_buffer(Byte_Buffer* buffer); 40 | 41 | virtual int register_network_handler(void); 42 | virtual int unregister_network_handler(void); 43 | 44 | virtual int close_handler(int cid); 45 | }; 46 | 47 | class Endpoint { 48 | typedef Object_Pool Svc_Pool; 49 | typedef Svc_Static_List Svc_List; 50 | public: 51 | Endpoint(void); 52 | virtual ~Endpoint(void); 53 | 54 | virtual int init(Endpoint_Info &endpoint_info) { endpoint_info_ = endpoint_info; return 0; } 55 | virtual int start(void) { return 0; } 56 | 57 | inline Endpoint_Accept &accept(void) { return accept_; } 58 | inline Endpoint_Connect &connect(void) { return connect_; } 59 | inline Endpoint_Network &network(void) { return network_; } 60 | inline Endpoint_Info &endpoint_info(void) { return endpoint_info_; } 61 | 62 | //创建数据buffer/回收数据buffer 63 | Byte_Buffer *pop_buffer(int cid) { return buffer_pool_group_.pop_buffer(cid); } 64 | int push_buffer(int cid, Byte_Buffer *buffer) { return buffer_pool_group_.push_buffer(cid, buffer); } 65 | 66 | //发送数据buffer 67 | int send_buffer(int cid, Byte_Buffer &buffer); 68 | 69 | //投递数据buffer 70 | virtual void post_buffer(Byte_Buffer* buffer) { } 71 | //投递掉线cid 72 | virtual void post_drop_cid(int cid) { } 73 | 74 | //创建svc/回收svc/查找svc 75 | Svc *pop_svc(int connfd); 76 | int push_svc(int cid); 77 | Svc *find_svc(int cid); 78 | 79 | int get_svc_info(Svc_Info &svc_info); 80 | void free_pool(void); 81 | 82 | private: 83 | Svc_List svc_list_; 84 | Svc_Pool svc_pool_; 85 | Buffer_Pool_Group buffer_pool_group_; 86 | 87 | Endpoint_Accept accept_; 88 | Endpoint_Connect connect_; 89 | Endpoint_Network network_; 90 | Endpoint_Info endpoint_info_; 91 | }; 92 | 93 | #endif /* ENDPOINT_H_ */ 94 | -------------------------------------------------------------------------------- /nodelib/network/Epoll_Watcher.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Epoll_Watcher.h 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | * 7 | * 底层使用epoll实现,主要功能为io事件回调、心跳超时机制、毫秒级定时器 8 | * 9 | */ 10 | 11 | #ifndef EPOLL_WATCHER_H_ 12 | #define EPOLL_WATCHER_H_ 13 | 14 | #include 15 | #include 16 | #include //使用std::unordered_map, 需添加-std=c++0x参数 -D__GXX_EXPERIMENTAL_CXX0X__ 17 | #include "Event_Handler.h" 18 | #include "Object_Pool.h" 19 | 20 | class Epoll_Watcher : public Event_Handler { 21 | //Timer事件 22 | typedef std::priority_queue, Event_Handler::greater> Timer_Queue; 23 | typedef std::unordered_set Event_Timer_Set; 24 | //IO事件 25 | typedef std::vector Event_Map; 26 | //心跳事件 27 | typedef std::unordered_map Heart_Map; 28 | typedef RE_Lock Mutex; 29 | public: 30 | /** 31 | * type可以指定IO附带心跳机制: WITH_IO_HEARTBEAT 32 | * heart_second制定IO心跳超时时间 33 | */ 34 | Epoll_Watcher(int type = 0, int heart_second = 30); 35 | virtual ~Epoll_Watcher(void); 36 | 37 | /** 38 | * 添加监听事件 39 | * op可以为EVENT_INPUT, EVENT_OUTPUT, EVENT_TIMEOUT等位集合 40 | * EVENT_INPUT, EVENT_OUTPUT, EVENT_ONCE_IO_IN, EVENT_ONCE_IO_OUT为监听IO事件 41 | * EVENT_TIMEOUT, EVENT_ONCE_TIMER为监听定时器事件 42 | * tv为定时器事件指定的间隔时间 43 | */ 44 | virtual int add(Event_Handler *evh, int op, Time_Value *tv = NULL); 45 | //移除eh的IO/定时器事件监听 46 | virtual int remove(Event_Handler *eh); 47 | 48 | //开始事件监听 49 | virtual int loop(void); 50 | //结束事件监听循环 51 | virtual int end_loop(void); 52 | 53 | //使阻塞的epoll_wait返回, 执行新的定时器处理函数 54 | virtual int notify(void); 55 | 56 | private: 57 | //开启epoll 58 | int open(void); 59 | //开启io事件 60 | int io_open(void); 61 | //开始定时器事件 62 | int timer_open(void); 63 | 64 | //添加io事件 65 | int add_io(Event_Handler *evh, int op); 66 | //添加定时器事件 67 | int add_timer(Event_Handler *evh, int op, Time_Value *tv); 68 | //移除io事件 69 | int remove_io(Event_Handler *evh); 70 | //移除定时器事件 71 | int remove_timer(Event_Handler *evh); 72 | 73 | //计算epoll_wait的等待时间 74 | int calculate_timeout(void); 75 | //处理已到期定时器事件 76 | void process_timer_event(void); 77 | //处理IO事件 78 | void watcher_loop(void); 79 | 80 | //EPOLLIN事件处理 81 | int handle_input(void); 82 | //心跳定时器处理 83 | int handle_timeout(const Time_Value &tv); 84 | //下次心跳索引 85 | inline int next_heart_idx(void) { return (io_heart_idx_ + 1) % 2; } 86 | 87 | private: 88 | int type_; //表示epoll自身事件类型,是否监听io心跳事件 89 | bool end_flag_; //epoll监听结束标记 90 | int epfd_; //epoll句柄 91 | int max_events_; //最大监听事件数量 92 | struct epoll_event *events_; 93 | 94 | Event_Map pending_io_map_; //io事件map 95 | int io_heart_idx_, heart_second_; //心跳索引 96 | Heart_Map io_heart_map_[2]; //心跳io事件 97 | Mutex io_lock_; 98 | 99 | Timer_Queue tq_; //时间优先队列(最小堆) 100 | Event_Timer_Set timer_set_; //定时器集合 101 | Mutex tq_lock_; 102 | 103 | int pipe_fd_[2]; //notify管道 104 | }; 105 | 106 | #endif /* EPOLL_WATCHER_H_ */ 107 | -------------------------------------------------------------------------------- /nodelib/network/Event_Handler.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Event_Handler.cpp 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef EVENT_HANDLER_H_ 9 | #define EVENT_HANDLER_H_ 10 | 11 | #include "Time_Value.h" 12 | 13 | class Epoll_Watcher; 14 | class Event_Handler { 15 | public: 16 | class greater { 17 | public: 18 | inline bool operator()(const Event_Handler *a, const Event_Handler *b) { 19 | return (a->get_absolute_tv()) > (b->get_absolute_tv()); 20 | } 21 | }; 22 | 23 | Event_Handler(void) : io_flag(0), fd_(0), timer_flag(0), heart_idx_(0) { } 24 | virtual ~Event_Handler(void) { } 25 | 26 | //callback interface 27 | virtual int handle_input(void) { 28 | return 0; 29 | } 30 | 31 | virtual int handle_output(void) { 32 | return 0; 33 | } 34 | 35 | virtual int handle_close(void) { 36 | return 0; 37 | } 38 | 39 | virtual int handle_timeout(const Time_Value &tv) { 40 | return 0; 41 | } 42 | 43 | int get_fd(void) const { 44 | return fd_; 45 | } 46 | 47 | void set_fd(int fd) { 48 | fd_ = fd; 49 | } 50 | 51 | void set_tv(Time_Value &ab_tv) { 52 | this->absolute_tv_ = ab_tv; 53 | } 54 | 55 | void set_tv(Time_Value &ab_tv, Time_Value &re_tv) { 56 | this->absolute_tv_ = ab_tv; 57 | this->relative_tv_ = re_tv; 58 | } 59 | 60 | const Time_Value &get_absolute_tv(void) const { 61 | return absolute_tv_; 62 | } 63 | 64 | Time_Value &get_relative_tv(void) { 65 | return relative_tv_; 66 | } 67 | 68 | int get_timer_flag(void) const { 69 | return timer_flag; 70 | } 71 | 72 | void set_timer_flag(int flag) { 73 | timer_flag |= flag; 74 | } 75 | 76 | int get_io_flag(void) const { 77 | return io_flag; 78 | } 79 | 80 | void set_io_flag(int flag) { 81 | io_flag |= flag; 82 | } 83 | 84 | int get_heart_idx(void) const { 85 | return heart_idx_; 86 | } 87 | 88 | void set_heart_idx(int idx) { 89 | heart_idx_ = idx; 90 | } 91 | 92 | void reset(void) { 93 | io_flag = 0; 94 | fd_ = 0; 95 | timer_flag = 0; 96 | absolute_tv_ = relative_tv_ = Time_Value::zero; 97 | heart_idx_ = 0; 98 | } 99 | 100 | private: 101 | int io_flag; 102 | int fd_; 103 | int timer_flag; 104 | Time_Value absolute_tv_, relative_tv_; 105 | int heart_idx_; 106 | }; 107 | 108 | #endif /* EVENT_HANDLER_H_ */ 109 | -------------------------------------------------------------------------------- /nodelib/network/Http_Client.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Http_Client.h 3 | * 4 | * Created on: Aug 15,2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef HTTP_CLIENT_H_ 9 | #define HTTP_CLIENT_H_ 10 | 11 | #include 12 | #include 13 | #include "Base_Define.h" 14 | 15 | class Http_Client 16 | { 17 | public: 18 | Http_Client(void); 19 | ~Http_Client(void); 20 | 21 | CURLcode post(const std::string & str_url, const std::string & str_post, std::string & str_response); 22 | CURLcode get(const std::string & str_url, std::string & str_response); 23 | std::string upload_byte_file(const std::string &str_url, void* data, int data_len); 24 | bool download_byte_file(const std::string &str_url, Data_Info* data_info); 25 | }; 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /nodelib/network/Http_Parser_Wrap.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/nodelib/network/Http_Parser_Wrap.h -------------------------------------------------------------------------------- /nodelib/network/Network.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Network.cpp 3 | * 4 | * Created on: Oct 20, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "Base_Function.h" 9 | #include "Endpoint.h" 10 | #include "Network.h" 11 | 12 | Network::Network(void): 13 | endpoint_(0), 14 | reactor_(0), 15 | svc_map_(max_fd()), 16 | register_timer_(false), 17 | heartbeat_tv_(0) 18 | { } 19 | 20 | Network::~Network(void) { 21 | fini(); 22 | } 23 | 24 | int Network::init(Endpoint *endpoint, int heartbeat_timeout) { 25 | endpoint_ = endpoint; 26 | heartbeat_timeout_ = heartbeat_timeout; 27 | heartbeat_tv_ = Time_Value::gettimeofday() + Time_Value(heartbeat_timeout_, 0); 28 | 29 | if ((reactor_ = new Epoll_Watcher()) == 0) { 30 | LOG_FATAL("network new Epoll_Watcher error"); 31 | } 32 | 33 | //注册发送数据定时器 34 | register_timer(); 35 | return 0; 36 | } 37 | 38 | int Network::fini(void) { 39 | if (reactor_) { 40 | reactor_->end_loop(); 41 | delete reactor_; 42 | reactor_ = 0; 43 | } 44 | return 0; 45 | } 46 | 47 | void Network::run_handler(void) { 48 | reactor_->loop(); 49 | } 50 | 51 | int Network::process_drop(void) { 52 | int cid = 0; 53 | Svc *svc = nullptr; 54 | while (!drop_list_.empty()) { 55 | cid = drop_list_.pop_front(); 56 | if ((svc = find_svc(cid)) != nullptr) { 57 | svc->set_closed(true); 58 | svc->unregister_network_handler(); 59 | } 60 | drop_handler(cid); 61 | } 62 | 63 | return 0; 64 | } 65 | 66 | int Network::register_svc(Svc *svc) { 67 | reactor_->add(svc, EVENT_INPUT); 68 | GUARD(Svc_Lock, mon, svc_map_lock_); 69 | svc_map_.insert(std::make_pair(svc->get_cid(), svc)); 70 | return 0; 71 | } 72 | 73 | int Network::unregister_svc(Svc *svc) { 74 | reactor_->remove(svc); 75 | GUARD(Svc_Lock, mon, svc_map_lock_); 76 | svc_map_.erase(svc->get_cid()); 77 | return 0; 78 | } 79 | 80 | int Network::drop_handler(int cid) { 81 | LOG_TRACE("SHOULD NOT HERE"); 82 | return 0; 83 | } 84 | 85 | Svc *Network::find_svc(int cid) { 86 | LOG_TRACE("SHOULD NOT HERE"); 87 | return 0; 88 | } 89 | 90 | int Network::register_timer(void) { 91 | if (!register_timer_) { 92 | Time_Value send_interval = Time_Value(0, 10 * 1000); 93 | reactor_->add(this, EVENT_TIMEOUT, &send_interval); 94 | register_timer_ = true; 95 | } 96 | 97 | return 0; 98 | } 99 | 100 | int Network::handle_timeout(const Time_Value &tv) { 101 | process_drop(); 102 | 103 | bool heartbeat_timeout = false; 104 | if(heartbeat_timeout_ > 0 && tv >= heartbeat_tv_) { 105 | heartbeat_tv_ = tv + Time_Value(heartbeat_timeout_, 0); 106 | heartbeat_timeout = true; 107 | } 108 | GUARD(Svc_Lock, mon, svc_map_lock_); 109 | for (Svc_Map::iterator iter = svc_map_.begin(); iter != svc_map_.end(); ++iter) { 110 | if(iter->second->closed()) { 111 | continue; 112 | } 113 | 114 | //发送svc数据 115 | if(iter->second->send_data()) { 116 | int ret = iter->second->handle_send(); 117 | if(ret <= 0) { 118 | iter->second->set_send_data(false); 119 | } 120 | } 121 | 122 | if(heartbeat_timeout) { 123 | //心跳到时时候,如果svc是活的,就将svc设置为死的,否则关闭svc 124 | if(iter->second->alive()) { 125 | iter->second->set_alive(false); 126 | } 127 | else { 128 | LOG_WARN("heartbeat_timeout, close svc, endpoint:%s cid:%d fd:%d", endpoint_->endpoint_info().endpoint_name.c_str(), 129 | iter->second->get_cid(), iter->second->get_fd()); 130 | iter->second->handle_close(); 131 | } 132 | } 133 | } 134 | return 0; 135 | } 136 | -------------------------------------------------------------------------------- /nodelib/network/Network.h: -------------------------------------------------------------------------------- 1 | /* 2 | * NetWork.h 3 | * 4 | * Created on: Oct 20, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef NETWORK_H_ 9 | #define NETWORK_H_ 10 | 11 | #include "List.h" 12 | #include "Thread.h" 13 | #include "Epoll_Watcher.h" 14 | #include "Svc.h" 15 | 16 | class Endpoint; 17 | class Network: public Thread, public Event_Handler { 18 | typedef Mutex_Lock Svc_Lock; 19 | typedef std::unordered_map Svc_Map; 20 | typedef List Drop_List; 21 | public: 22 | Network(void); 23 | virtual ~Network(void); 24 | 25 | int init(Endpoint *endpoint, int heartbeat_intverval); 26 | int fini(void); 27 | 28 | virtual void run_handler(void); 29 | 30 | inline int push_drop(int cid) { 31 | drop_list_.push_back(cid); 32 | reactor_->notify(); 33 | return 0; 34 | } 35 | int process_drop(void); 36 | 37 | int register_svc(Svc *svc); 38 | int unregister_svc(Svc *svc); 39 | 40 | virtual int drop_handler(int cid); 41 | virtual Svc *find_svc(int cid); 42 | 43 | int register_timer(void); 44 | virtual int handle_timeout(const Time_Value &tv); 45 | 46 | protected: 47 | Endpoint *endpoint_; 48 | 49 | private: 50 | Epoll_Watcher *reactor_; 51 | Drop_List drop_list_; //掉线cid列表 52 | 53 | Svc_Lock svc_map_lock_; //svc map锁 54 | Svc_Map svc_map_; //svc信息 55 | 56 | bool register_timer_; //是否注册定时器 57 | int heartbeat_timeout_; //心跳超时时间 58 | Time_Value heartbeat_tv_; //心跳tick 59 | }; 60 | 61 | #endif /* NETWORK_H_ */ 62 | -------------------------------------------------------------------------------- /nodelib/network/Svc.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Svc.h 3 | * 4 | * Created on: Dec 16,2015 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef SVC_H_ 9 | #define SVC_H_ 10 | 11 | #include "Buffer_List.h" 12 | #include "Event_Handler.h" 13 | 14 | const static int SVC_MAX_LIST_SIZE = 10240; 15 | const static int SVC_MAX_PACK_SIZE = 60 * 1024; 16 | 17 | class Svc; 18 | class Svc_Handler { 19 | public: 20 | typedef Buffer_List Data_List; 21 | typedef std::vector Buffer_Vector; 22 | public: 23 | Svc_Handler(void); 24 | virtual ~Svc_Handler(void); 25 | 26 | void reset(void); 27 | void set_parent(Svc *parent) { parent_ = parent; } 28 | 29 | int push_recv_buffer(Byte_Buffer *buffer); 30 | int push_send_buffer(Byte_Buffer *buffer); 31 | 32 | virtual int handle_send(void) = 0; 33 | virtual int handle_pack(Buffer_Vector &buffer_vec) = 0; 34 | 35 | protected: 36 | Svc *parent_; 37 | Data_List recv_buffer_list_; 38 | Data_List send_buffer_list_; 39 | 40 | size_t max_list_size_; 41 | size_t max_pack_size_; 42 | }; 43 | 44 | class Endpoint; 45 | class Svc: public Event_Handler { 46 | public: 47 | typedef std::vector Buffer_Vector; 48 | 49 | Svc(void); 50 | virtual ~Svc(void); 51 | 52 | void reset(void); 53 | 54 | virtual Byte_Buffer *pop_buffer(int cid); 55 | virtual int push_buffer(int cid, Byte_Buffer *buffer); 56 | virtual int post_buffer(Byte_Buffer* buffer); 57 | 58 | virtual int register_network_handler(void); 59 | virtual int unregister_network_handler(void); 60 | 61 | virtual int close_handler(int cid); 62 | 63 | int create_handler(int protocol_type); 64 | 65 | virtual int handle_input(void); 66 | virtual int handle_send(void); 67 | virtual int handle_close(void); 68 | int close_fd(void); 69 | 70 | inline int push_recv_buffer(Byte_Buffer *buffer) { 71 | if (closed_) { 72 | return -1; 73 | } else { 74 | return handler_->push_recv_buffer(buffer); 75 | } 76 | } 77 | inline int push_send_buffer(Byte_Buffer *buffer) { 78 | if (closed_) { 79 | return -1; 80 | } else { 81 | return handler_->push_send_buffer(buffer); 82 | } 83 | } 84 | 85 | void set_endpoint(Endpoint *endpoint); 86 | 87 | inline void set_cid(int cid) { cid_ = cid; } 88 | inline int get_cid(void) { return cid_; } 89 | 90 | inline void set_closed(bool is_closed) { closed_ = is_closed; } 91 | inline bool closed(void) { return closed_; } 92 | 93 | inline void set_alive(bool alive) { alive_ = alive; } 94 | inline bool alive(void) { return alive_; } 95 | 96 | inline void set_client(bool client) { client_ = client; } 97 | inline bool client(void) { return client_; } 98 | 99 | inline void set_reg_network(bool reg_network) { reg_network_ = reg_network; } 100 | inline bool reg_network(void) { return reg_network_; } 101 | 102 | inline void set_send_data(bool send_data) { send_data_ = send_data; } 103 | inline bool send_data(void) { return send_data_; } 104 | 105 | inline void set_peer_addr(void) { get_peer_addr(peer_ip_, peer_port_); } 106 | int get_peer_addr(std::string &ip, int &port); 107 | int get_local_addr(std::string &ip, int &port); 108 | 109 | inline std::string &get_peer_ip() { return peer_ip_; } 110 | inline int get_peer_port() { return peer_port_; } 111 | 112 | protected: 113 | Endpoint *endpoint_; 114 | 115 | private: 116 | int cid_; //网络连接cid 117 | bool closed_; //是否关闭 118 | bool alive_; //是否活跃的连接 119 | bool client_; //是否为client 120 | bool reg_network_; //是否注册网络 121 | bool send_data_; //是否发送数据 122 | std::string peer_ip_; //client ip 123 | int peer_port_; //client port 124 | 125 | Svc_Handler *handler_; //svc处理句柄 126 | }; 127 | 128 | inline void Svc::reset(void) { 129 | cid_ = 0; 130 | closed_ = false; 131 | alive_ = false; 132 | client_ = false; 133 | reg_network_ = false; 134 | send_data_ = false; 135 | peer_ip_.clear(); 136 | peer_port_ = 0; 137 | 138 | if (handler_) { 139 | handler_->reset(); 140 | delete handler_; 141 | handler_ = 0; 142 | } 143 | endpoint_ = 0; 144 | Event_Handler::reset(); 145 | } 146 | 147 | #endif /* SVC_H_ */ 148 | -------------------------------------------------------------------------------- /nodelib/network/Svc_Http.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Svc_Http.cpp 3 | * 4 | * Created on: Aug 16,2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include 9 | #include 10 | #include "Bit_Buffer.h" 11 | #include "Http_Parser_Wrap.h" 12 | #include "Svc_Http.h" 13 | 14 | Svc_Http::Svc_Http(): Svc_Handler() {} 15 | 16 | Svc_Http::~Svc_Http() {} 17 | 18 | int Svc_Http::handle_send(void) { 19 | if (parent_->closed()) 20 | return -1; 21 | 22 | int cid = parent_->get_cid(); 23 | Byte_Buffer *front_buf = 0; 24 | Bit_Buffer data_buf; 25 | while (!send_buffer_list_.empty()) { 26 | front_buf = send_buffer_list_.front(); 27 | 28 | //构建http消息头 29 | data_buf.reset(); 30 | data_buf.set_ary(front_buf->get_read_ptr(), front_buf->readable_bytes()); 31 | std::string str_content = ""; 32 | data_buf.read_str(str_content); 33 | int content_len = str_content.length(); 34 | int total_len = content_len + strlen(HTTP_RESPONSE_HTML) + 32; 35 | char *str_http = new char[total_len]; 36 | snprintf(str_http, total_len, HTTP_RESPONSE_HTML, content_len, str_content.c_str()); 37 | 38 | //将buffer内容写入到socket 39 | size_t sum_bytes = strlen(str_http); 40 | int ret = ::write(parent_->get_fd(), str_http, sum_bytes); 41 | //不要忘记删除内存 42 | delete []str_http; 43 | if (ret == -1) { 44 | if (errno == EINTR) { //被打断, 重写 45 | continue; 46 | } 47 | else if (errno == EWOULDBLOCK) { //EAGAIN,下一次超时再写 48 | return 1; 49 | } 50 | else { //其他错误,丢掉该客户端全部数据 51 | LOG_ERROR("writev error, cid:%d ip:%s port:%d", cid, parent_->get_peer_ip().c_str(), parent_->get_peer_port()); 52 | parent_->handle_close(); 53 | return ret; 54 | } 55 | } else { 56 | if ((size_t)ret == sum_bytes) { //本次全部写完, 尝试继续写 57 | parent_->push_buffer(cid, front_buf); 58 | send_buffer_list_.pop_front(); 59 | continue; 60 | } 61 | else { //未写完, 下一次超时再写 62 | return ret; 63 | } 64 | } 65 | } 66 | return 0; 67 | } 68 | 69 | int Svc_Http::handle_pack(Buffer_Vector &buffer_vec) { 70 | int32_t eid = 0; 71 | int32_t cid = 0; 72 | Byte_Buffer *front_buf = 0; 73 | 74 | while (! recv_buffer_list_.empty()) { 75 | front_buf = recv_buffer_list_.front(); 76 | if (! front_buf) { 77 | LOG_ERROR("front_buf == 0"); 78 | continue; 79 | } 80 | 81 | front_buf->read_int32(eid); 82 | front_buf->read_int32(cid); 83 | if (front_buf->readable_bytes() <= 0) { //数据块异常, 关闭该连接 84 | LOG_ERROR("cid:%d fd:%d, buffer read bytes<0", cid, parent_->get_fd()); 85 | recv_buffer_list_.pop_front(); 86 | front_buf->reset(); 87 | parent_->push_buffer(parent_->get_cid(), front_buf); 88 | parent_->handle_close(); 89 | return -1; 90 | } 91 | 92 | Http_Parser_Wrap http_parser; 93 | http_parser.parse_http_content(front_buf->get_read_ptr(), front_buf->readable_bytes()); 94 | 95 | Byte_Buffer *data_buf = parent_->pop_buffer(cid); 96 | data_buf->reset(); 97 | data_buf->write_int32(eid); 98 | data_buf->write_int32(cid); 99 | data_buf->write_uint8(RPC_PKG << 4 | HTTP); 100 | data_buf->write_string(http_parser.get_body_content()); 101 | buffer_vec.push_back(data_buf); 102 | recv_buffer_list_.pop_front(); 103 | } 104 | 105 | return 0; 106 | } 107 | -------------------------------------------------------------------------------- /nodelib/network/Svc_Http.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Svc_Http.h 3 | * 4 | * Created on: Aug 16,2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef SVC_HTTP_H_ 9 | #define SVC_HTTP_H_ 10 | 11 | #include "Svc.h" 12 | 13 | #define HTTP_RESPONSE_HTML "HTTP/1.1 200 OK\r\n"\ 14 | "Connection:close\r\n"\ 15 | "Content-Length:%d\r\n"\ 16 | "Content-Type:text/html;charset=utf-8\r\n\r\n%s" 17 | 18 | class Svc_Http : public Svc_Handler { 19 | public: 20 | Svc_Http(void); 21 | virtual ~Svc_Http(void); 22 | 23 | virtual int handle_send(void); 24 | virtual int handle_pack(Buffer_Vector &buffer_vec); 25 | }; 26 | 27 | #endif /* SVC_HTTP_H_ */ 28 | -------------------------------------------------------------------------------- /nodelib/network/Svc_Tcp.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Svc_Tcp.h 3 | * 4 | * Created on: Apr 19,2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef SVC_TCP_H_ 9 | #define SVC_TCP_H_ 10 | 11 | #include "Svc.h" 12 | 13 | class Svc_Tcp : public Svc_Handler { 14 | public: 15 | Svc_Tcp(void); 16 | virtual ~Svc_Tcp(void); 17 | 18 | virtual int handle_send(void); 19 | virtual int handle_pack(Buffer_Vector &buffer_vec); 20 | }; 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /nodelib/network/Svc_WebSocket.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Svc_Websocket.h 3 | * 4 | * Created on: Apr 19,2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef SVC_WEBSOCKET_H_ 9 | #define SVC_WEBSOCKET_H_ 10 | 11 | #include "Svc.h" 12 | 13 | #define MAGIC_KEY "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" 14 | 15 | class Svc_Websocket : public Svc_Handler { 16 | public: 17 | Svc_Websocket(void); 18 | virtual ~Svc_Websocket(void); 19 | 20 | void reset(void); 21 | virtual int handle_send(void); 22 | virtual int handle_pack(Buffer_Vector &buffer_vec); 23 | 24 | private: 25 | //websocket第一步握手 26 | int handshake(Byte_Buffer *buffer); 27 | //解析websocket帧头,获取buffer内容 28 | Byte_Buffer *get_frame_buffer(int32_t eid, int16_t payload_length, uint8_t *masking_key, Byte_Buffer *buffer); 29 | //包装websocket帧头 30 | Byte_Buffer *make_frame_buffer(Byte_Buffer *buffer, uint8_t *op = NULL); 31 | 32 | private: 33 | bool connected_; 34 | }; 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /nodelib/node/Hot_Update.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Hot_Update.cpp 3 | * 4 | * Created on: Nov 21,2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "V8_Manager.h" 16 | #include "Hot_Update.h" 17 | 18 | Hot_Update::Hot_Update() {} 19 | 20 | Hot_Update::~Hot_Update() {} 21 | 22 | Hot_Update *Hot_Update::instance_; 23 | 24 | Hot_Update *Hot_Update::instance(void) { 25 | if (! instance_) 26 | instance_ = new Hot_Update; 27 | return instance_; 28 | } 29 | 30 | void Hot_Update::run_handler(void) { 31 | while (true) { 32 | Time_Value::sleep(Time_Value(15)); 33 | //遍历检查每个文件md5,发现不同的就更新该文件 34 | for (Md5_Str_Map::iterator iter = md5_str_map_.begin(); iter != md5_str_map_.end(); ++iter) { 35 | std::string md5_str = calc_file_md5(iter->first); 36 | if(md5_str != iter->second) { 37 | iter->second = md5_str; 38 | V8_MANAGER->push_hotupdate_file(iter->first); 39 | } 40 | } 41 | } 42 | } 43 | 44 | int Hot_Update::init(const std::vector &folder_list) { 45 | for(std::vector::const_iterator iter = folder_list.begin(); iter != folder_list.end(); ++iter) { 46 | init_file_md5(*iter); 47 | } 48 | return 0; 49 | } 50 | 51 | int Hot_Update::init_file_md5(const std::string folder_path) { 52 | struct dirent *ent = NULL; 53 | struct stat sbuf; 54 | DIR *pDir = NULL; 55 | pDir = opendir(folder_path.c_str()); 56 | if (pDir == NULL) { 57 | //被当作目录,但是执行opendir后发现又不是目录,比如软链接就会发生这样的情况。 58 | LOG_ERROR("open dir error, folder_path:%s", folder_path.c_str()); 59 | return -1; 60 | } 61 | 62 | //遍历目录下面的每个文件 63 | while (NULL != (ent = readdir(pDir))) { 64 | if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) { 65 | continue; 66 | } 67 | 68 | std::string file_path = folder_path + ent->d_name; 69 | //获取文件属性 70 | if (lstat(file_path.c_str(), &sbuf) < 0) { 71 | LOG_ERROR("lstat file error, file_path:%s", file_path.c_str()); 72 | continue; 73 | } 74 | 75 | if (S_ISREG(sbuf.st_mode)) { 76 | //如果是文件,就计算md5,插入map 77 | if (strstr(ent->d_name, ".js") || strstr(ent->d_name, ".xml")) { 78 | std::string md5_str = calc_file_md5(file_path); 79 | if (md5_str != "") { 80 | md5_str_map_.insert(std::make_pair(file_path, md5_str)); 81 | } 82 | } 83 | } else if (S_ISDIR(sbuf.st_mode)) { 84 | //如果是目录,就递归遍历 85 | file_path += "/"; 86 | init_file_md5(file_path); 87 | } 88 | } 89 | 90 | if (pDir) { 91 | closedir(pDir); 92 | pDir = NULL; 93 | } 94 | return 0; 95 | } 96 | 97 | std::string Hot_Update::calc_file_md5(const std::string &file_path) { 98 | MD5_CTX md5; 99 | unsigned char md[16]; 100 | char tmp[33] = {'\0'}; 101 | int length = 0, i = 0; 102 | char buffer[1024] = {0}; 103 | std::string hash = ""; 104 | MD5_Init(&md5); 105 | 106 | int fd = 0; 107 | if ((fd = open(file_path.c_str(), O_RDONLY)) < 0) { 108 | LOG_ERROR("open file error, file_path:%s", file_path.c_str()); 109 | return hash; 110 | } 111 | 112 | while (true) { 113 | length = read(fd, buffer, 1024); 114 | if (length == 0 || ((length == -1) && (errno != EINTR))) { 115 | break; 116 | } else if (length > 0) { 117 | MD5_Update(&md5, buffer, length); 118 | } 119 | } 120 | 121 | MD5_Final(md, &md5); 122 | for(i=0; i < 16; i++) { 123 | sprintf(tmp, "%02X", md[i]); 124 | hash += (std::string)tmp; 125 | } 126 | close(fd); 127 | 128 | return hash; 129 | } 130 | -------------------------------------------------------------------------------- /nodelib/node/Hot_Update.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Hot_Update.h 3 | * 4 | * Created on: Nov 21,2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef HOT_UPDATE_H_ 9 | #define HOT_UPDATE_H_ 10 | 11 | #include 12 | #include 13 | #include "Thread.h" 14 | 15 | class Hot_Update: public Thread { 16 | typedef std::unordered_map Md5_Str_Map; //file_path--md5_str 17 | public: 18 | Hot_Update(); 19 | virtual ~Hot_Update(); 20 | 21 | static Hot_Update *instance(void); 22 | virtual void run_handler(void); 23 | int init(const std::vector &folder_list); 24 | 25 | private: 26 | int init_file_md5(const std::string folder_path); 27 | std::string calc_file_md5(const std::string &file_path); 28 | 29 | private: 30 | static Hot_Update *instance_; 31 | Md5_Str_Map md5_str_map_; 32 | }; 33 | 34 | #define HOT_UPDATE Hot_Update::instance() 35 | 36 | #endif /* HOTUPDATE_H_ */ 37 | -------------------------------------------------------------------------------- /nodelib/node/Node_Define.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Node_Define.cpp 3 | * 4 | * Created on: Sep 20, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "Bit_Buffer.h" 9 | #include "Node_Define.h" 10 | 11 | void Node_Info::serialize(Bit_Buffer &buffer) { 12 | buffer.write_int(node_type, 32); 13 | buffer.write_int(node_id, 32); 14 | buffer.write_int(endpoint_gid, 32); 15 | buffer.write_int(max_session_count, 32); 16 | buffer.write_str(node_name.c_str()); 17 | buffer.write_str(node_ip.c_str()); 18 | 19 | uint endpoint_size = endpoint_list.size(); 20 | buffer.write_uint(endpoint_size, 8); 21 | for (uint i = 0; i < endpoint_size; ++i) { 22 | endpoint_list[i].serialize(buffer); 23 | } 24 | } 25 | 26 | void Node_Info::deserialize(Bit_Buffer &buffer) { 27 | node_type = buffer.read_int(32); 28 | node_id = buffer.read_int(32); 29 | endpoint_gid = buffer.read_int(32); 30 | max_session_count = buffer.read_int(32); 31 | buffer.read_str(node_name); 32 | buffer.read_str(node_ip); 33 | 34 | uint endpoint_size = buffer.read_uint(8); 35 | Endpoint_Info endpoint_info; 36 | for (uint i = 0; i < endpoint_size; ++i) { 37 | endpoint_info.reset(); 38 | endpoint_info.deserialize(buffer); 39 | endpoint_list.push_back(endpoint_info); 40 | } 41 | } 42 | 43 | void Node_Info::reset(void) { 44 | node_type = 0; 45 | node_id = 0; 46 | node_name = ""; 47 | node_ip = ""; 48 | global_script = ""; 49 | main_script = ""; 50 | hotupdate_list.clear(); 51 | plugin_list.clear(); 52 | filter_list.clear(); 53 | endpoint_list.clear(); 54 | } 55 | -------------------------------------------------------------------------------- /nodelib/node/Node_Define.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Node_Define.h 3 | * 4 | * Created on: Sep 20, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef Node_DEFINE_H_ 9 | #define Node_DEFINE_H_ 10 | 11 | #include 12 | #include "Base_Define.h" 13 | #include "Time_Value.h" 14 | 15 | struct Drop_Info { 16 | int eid; 17 | int cid; 18 | Time_Value drop_time; 19 | 20 | Drop_Info(void) : eid(0), cid(-1), drop_time(Time_Value::gettimeofday()) {} 21 | Drop_Info(int eid_, int cid_) : eid(eid_), cid(cid_), drop_time(Time_Value::gettimeofday()) {} 22 | }; 23 | 24 | //消息过滤器,被过滤的消息,不会抛给脚本层,直接由C++处理 25 | struct Msg_Filter { 26 | int msg_type; //消息类型 27 | int min_msg_id; //最小消息id 28 | int max_msg_id; //最大消息id 29 | }; 30 | 31 | typedef std::vector Filter_List; 32 | typedef std::vector Endpoint_List; 33 | struct Node_Info { 34 | int node_type; //节点类型 35 | int node_id; //节点id 36 | int endpoint_gid; //端点组id 37 | int max_session_count; //单个进程最多能处理的session上限 38 | std::string node_name; //节点名称 39 | std::string node_ip; //节点ip 40 | std::string global_script; //js全局数据脚本路径 41 | std::string main_script; //js主脚本路径 42 | std::vector hotupdate_list;//可以热更新的文件夹列表 43 | std::vector plugin_list; //插件列表 44 | Filter_List filter_list; //消息过滤器列表 45 | Endpoint_List endpoint_list;//线程列表 46 | 47 | void serialize(Bit_Buffer &buffer); 48 | void deserialize(Bit_Buffer &buffer); 49 | void reset(void); 50 | }; 51 | 52 | struct Node_Status { 53 | int start_time; //服务器开启时间 54 | int64_t total_send; //总共发送字节数 55 | int64_t total_recv; //总共接收字节数 56 | int send_per_sec; //每秒发生字节数 57 | int recv_per_sec; //每秒接收字节数 58 | int task_count; //当前任务数量 59 | }; 60 | 61 | #endif /* Node_DEFINE_H_ */ 62 | -------------------------------------------------------------------------------- /nodelib/node/Node_Endpoint.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Node_Endpoint.cpp 3 | * 4 | * Created on: Nov 7, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "Node_Endpoint.h" 9 | 10 | Server::Server(void) { } 11 | 12 | Server::~Server(void) { } 13 | 14 | int Server::init(Endpoint_Info &endpoint_info) { 15 | Endpoint::init(endpoint_info); 16 | 17 | accept().init(this, endpoint_info.server_port); 18 | network().init(this, endpoint_info.heartbeat_timeout); 19 | return 0; 20 | } 21 | 22 | int Server::start(void) { 23 | accept().thr_create(); 24 | network().thr_create(); 25 | return 0; 26 | } 27 | 28 | //////////////////////////////////////////////////////////////////////////////// 29 | Connector::Connector(void) : cid_(-1) { } 30 | 31 | Connector::~Connector(void) { } 32 | 33 | int Connector::init(Endpoint_Info &endpoint_info) { 34 | Endpoint::init(endpoint_info); 35 | 36 | connect().init(this); 37 | network().init(this, endpoint_info.heartbeat_timeout); 38 | return 0; 39 | } 40 | 41 | int Connector::start(void) { 42 | network().thr_create(); 43 | return 0; 44 | } 45 | 46 | int Connector::connect_server(std::string ip, int port) { 47 | if (ip == "" && port == 0) { 48 | cid_ = connect().connect(endpoint_info().server_ip.c_str(), endpoint_info().server_port); 49 | } else { 50 | cid_ = connect().connect(ip.c_str(), port); 51 | } 52 | return cid_; 53 | } -------------------------------------------------------------------------------- /nodelib/node/Node_Endpoint.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Node_Endpoint.h 3 | * 4 | * Created on: Nov 7, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef NODE_ENDPOINT_H_ 9 | #define NODE_ENDPOINT_H_ 10 | 11 | #include "Endpoint.h" 12 | #include "V8_Manager.h" 13 | 14 | class Server: public Endpoint { 15 | public: 16 | Server(void); 17 | virtual ~Server(void); 18 | 19 | virtual int init(Endpoint_Info &endpoint_info); 20 | virtual int start(void); 21 | 22 | virtual void post_buffer(Byte_Buffer* buffer) { V8_MANAGER->push_buffer(buffer); } 23 | virtual void post_drop_cid(int cid) { 24 | if(endpoint_info().endpoint_type == CLIENT_SERVER) { 25 | V8_MANAGER->push_drop_cid(cid); 26 | } 27 | } 28 | }; 29 | 30 | class Connector: public Endpoint { 31 | public: 32 | Connector(void); 33 | virtual ~Connector(void); 34 | 35 | virtual int init(Endpoint_Info &endpoint_info); 36 | virtual int start(void); 37 | int connect_server(std::string ip = "", int port = 0); 38 | int get_cid(void) { return cid_; } 39 | 40 | virtual void post_buffer(Byte_Buffer* buffer) { V8_MANAGER->push_buffer(buffer); } 41 | virtual void post_drop_cid(int cid) { 42 | V8_MANAGER->push_drop_eid(endpoint_info().endpoint_id); 43 | } 44 | 45 | private: 46 | int cid_; 47 | }; 48 | 49 | #endif /* NODE_ENDPOINT_H_ */ 50 | -------------------------------------------------------------------------------- /nodelib/node/Node_Manager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Node_Manager.h 3 | * 4 | * Created on: Sep 20, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef NODE_MANAGER_H_ 9 | #define NODE_MANAGER_H_ 10 | 11 | #include "Xml.h" 12 | #include "Node_Endpoint.h" 13 | 14 | class Node_Manager { 15 | public: 16 | typedef Object_Pool Server_Pool; 17 | typedef Object_Pool Connector_Pool; 18 | typedef List Int_List; 19 | typedef std::unordered_map Endpoint_Map; //endpoint_id--endpoint 20 | typedef std::unordered_map Msg_Count_Map; //msg_id--msg_count 21 | public: 22 | static Node_Manager *instance(void); 23 | 24 | //初始化 25 | int init(int node_type, int node_id, int endpoint_gid, const std::string &node_name); 26 | int init_node_info(int endpoint_gid, Xml &xml, TiXmlNode* node); 27 | 28 | int connect_server(int eid); 29 | //通知daemon_server创建进程 30 | int fork_process(int node_type, int node_id, int endpoint_gid, std::string &node_name); 31 | //获取node堆栈 32 | int get_node_stack(int node_id, int eid, int cid, int sid); 33 | 34 | inline const Node_Info &node_info(void) { return node_info_; } 35 | //通知网络层掉线 36 | inline int push_drop(int eid, int cid); 37 | //回收消息buffer 38 | inline int push_buffer(int eid, int cid, Byte_Buffer *buffer); 39 | //消息过滤器,被过滤的消息,不抛给脚本层,直接由C++处理 40 | inline bool msg_filter(int msg_type, int msg_id); 41 | //发送消息 42 | int send_msg(Msg_Head &msg_head, char const *data, size_t len); 43 | 44 | //释放内存池自由节点 45 | int free_pool(void); 46 | //获得消息数量信息 47 | inline const Msg_Count_Map &msg_count_map(void) { return msg_count_map_; } 48 | //获得node状态 49 | const Node_Status &get_node_status(void); 50 | void reset_node_status(void); 51 | //字节统计 52 | inline void add_send_bytes(int send_bytes) { 53 | node_status_.total_send += send_bytes; 54 | node_status_.send_per_sec += send_bytes; 55 | } 56 | inline void add_recv_bytes(int recv_bytes) { 57 | node_status_.total_recv += recv_bytes; 58 | node_status_.recv_per_sec += recv_bytes; 59 | } 60 | inline void add_msg_count(int msg_id) { 61 | msg_count_map_[msg_id]++; 62 | } 63 | 64 | private: 65 | Node_Manager(void); 66 | virtual ~Node_Manager(void); 67 | Node_Manager(const Node_Manager &); 68 | const Node_Manager &operator=(const Node_Manager &); 69 | 70 | private: 71 | static Node_Manager *instance_; 72 | 73 | Server_Pool server_pool_; 74 | Connector_Pool connector_pool_; 75 | 76 | int msg_filter_count_; //消息过滤器数量 77 | Node_Info node_info_; //节点信息 78 | Endpoint_Map endpoint_map_; //通信端信息 79 | 80 | Msg_Count_Map msg_count_map_; //消息数量信息 81 | Time_Value node_status_tick_; //获取节点状态tick时间 82 | Node_Status node_status_; //节点状态 83 | }; 84 | 85 | #define NODE_MANAGER Node_Manager::instance() 86 | 87 | int Node_Manager::push_drop(int eid, int cid) { 88 | Endpoint_Map::iterator iter = endpoint_map_.find(eid); 89 | if (iter != endpoint_map_.end()) { 90 | iter->second->network().push_drop(cid); 91 | } 92 | return 0; 93 | } 94 | 95 | int Node_Manager::push_buffer(int eid, int cid, Byte_Buffer *buffer) { 96 | Endpoint_Map::iterator iter = endpoint_map_.find(eid); 97 | if (iter != endpoint_map_.end()) { 98 | iter->second->push_buffer(cid, buffer); 99 | } 100 | return 0; 101 | } 102 | 103 | bool Node_Manager::msg_filter(int msg_type, int msg_id) { 104 | for (int i = 0; i < msg_filter_count_; ++i) { 105 | if (msg_type == node_info_.filter_list[i].msg_type && msg_id >= node_info_.filter_list[i].min_msg_id 106 | && msg_id <= node_info_.filter_list[i].max_msg_id) { 107 | return true; 108 | } 109 | } 110 | return false; 111 | } 112 | 113 | #endif /* NODE_MANAGER_H_ */ 114 | -------------------------------------------------------------------------------- /nodelib/node/Node_Timer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Node_Timer.cpp 3 | * 4 | * Created on: Sep 20, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "V8_Manager.h" 9 | #include "Node_Timer.h" 10 | 11 | Timer_Handler::Timer_Handler(void) { } 12 | 13 | Timer_Handler::~Timer_Handler(void) { } 14 | 15 | int Timer_Handler::handle_timeout(const Time_Value &tv) { 16 | V8_MANAGER->push_tick(tv.sec()); 17 | NODE_TIMER->tick(tv); 18 | return 0; 19 | } 20 | 21 | Node_Timer::Node_Timer(void) { } 22 | 23 | Node_Timer::~Node_Timer(void) { } 24 | 25 | Node_Timer *Node_Timer::instance_; 26 | 27 | Node_Timer *Node_Timer::instance(void) { 28 | if (instance_ == 0) 29 | instance_ = new Node_Timer; 30 | return instance_; 31 | } 32 | 33 | void Node_Timer::run_handler(void) { 34 | Time_Value tv(0, 10 * 1000); 35 | watcher_.add(&timer_handler_, EVENT_TIMEOUT, &tv); 36 | watcher_.loop(); 37 | } 38 | 39 | void Node_Timer::register_handler(int timer_id, int internal, int first_tick) { 40 | V8_Timer *timer = timer_pool_.pop(); 41 | timer->timer_id = timer_id; 42 | timer->interval = internal; 43 | timer->next_tick = Time_Value::gettimeofday() + Time_Value(first_tick); 44 | timer_queue_.push(timer); 45 | } 46 | 47 | int Node_Timer::tick(const Time_Value &now){ 48 | while(!timer_queue_.empty() && (now > timer_queue_.top()->next_tick)) { 49 | V8_Timer *timer = timer_queue_.top(); 50 | timer_queue_.pop(); 51 | V8_MANAGER->push_timer(timer->timer_id); 52 | timer->next_tick += Time_Value(timer->interval / 1000, timer->interval % 1000 * 1000); 53 | timer_queue_.push(timer); 54 | } 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /nodelib/node/Node_Timer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Node_Timer.h 3 | * 4 | * Created on: Sep 20, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef NODE_TIMER_H_ 9 | #define NODE_TIMER_H_ 10 | 11 | #include "Epoll_Watcher.h" 12 | #include "Thread.h" 13 | #include "Priority_Queue.h" 14 | 15 | struct V8_Timer { 16 | int timer_id; //js层定时器编号 17 | int interval; //定时时间间隔(毫秒为单位) 18 | Time_Value next_tick; //下一次执行时间 19 | }; 20 | 21 | class V8_Timer_Compare { 22 | public: 23 | inline bool operator()(V8_Timer *t1, V8_Timer *t2) { 24 | return t1->next_tick > t2->next_tick; 25 | } 26 | }; 27 | 28 | class Timer_Handler: public Event_Handler { 29 | public: 30 | Timer_Handler(void); 31 | virtual ~Timer_Handler(void); 32 | 33 | virtual int handle_timeout(const Time_Value &tv); 34 | }; 35 | 36 | class Node_Timer: public Thread { 37 | typedef Object_Pool Timer_Pool; 38 | typedef Priority_Queue Timer_Queue; 39 | public: 40 | static Node_Timer *instance(void); 41 | virtual void run_handler(void); 42 | 43 | void register_handler(int timer_id, int internal, int first_tick); //注册js层定时器 44 | int tick(const Time_Value &now); 45 | 46 | private: 47 | Node_Timer(void); 48 | virtual ~Node_Timer(void); 49 | Node_Timer(const Node_Timer &); 50 | const Node_Timer &operator=(const Node_Timer &); 51 | 52 | private: 53 | static Node_Timer *instance_; 54 | Epoll_Watcher watcher_; 55 | Timer_Handler timer_handler_; 56 | Timer_Pool timer_pool_; 57 | Timer_Queue timer_queue_; 58 | }; 59 | 60 | #define NODE_TIMER Node_Timer::instance() 61 | 62 | #endif /* NODE_TIMER_H_ */ 63 | -------------------------------------------------------------------------------- /nodelib/struct/DB_Struct.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * DB_Struct.cpp 3 | * 4 | * Created on: Oct 21, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "DB_Struct.h" 9 | 10 | DB_Struct::DB_Struct() : 11 | Base_Struct(), 12 | db_name_(), 13 | table_name_(), 14 | index_name_(), 15 | index_type_() { } 16 | 17 | DB_Struct::~DB_Struct() { 18 | db_name_.clear(); 19 | table_name_.clear(); 20 | index_name_.clear(); 21 | index_type_.clear(); 22 | } 23 | 24 | int DB_Struct::init(Xml &xml, TiXmlNode *node) { 25 | if(node) { 26 | table_name_ = xml.get_attr_str(node, "table_name"); 27 | db_name_ = table_name_.substr(0, table_name_.find(".")); 28 | index_name_ = xml.get_attr_str(node, "index_name"); 29 | index_type_ = xml.get_attr_str(node, "index_type"); 30 | } 31 | 32 | //Base_Struct初始化放在最后面,因为Base_Struct初始化内部会遍历node节点 33 | return Base_Struct::init(xml, node); 34 | } -------------------------------------------------------------------------------- /nodelib/struct/DB_Struct.h: -------------------------------------------------------------------------------- 1 | /* 2 | * DB_Struct.h 3 | * 4 | * Created on: Oct 21, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef DB_STRUCT_H_ 9 | #define DB_STRUCT_H_ 10 | 11 | #include "Base_Struct.h" 12 | 13 | class DB_Struct: public Base_Struct { 14 | public: 15 | DB_Struct(); 16 | virtual ~DB_Struct(); 17 | 18 | virtual int init(Xml &xml, TiXmlNode *node); 19 | 20 | inline const std::string &table_name() { return table_name_; } 21 | inline const std::string &db_name() { return db_name_; } 22 | inline const std::string &index_name() { return index_name_; } 23 | inline const std::string &index_type() { return index_type_; } 24 | 25 | private: 26 | std::string db_name_; 27 | std::string table_name_; 28 | std::string index_name_; 29 | std::string index_type_; 30 | }; 31 | 32 | #endif /* DB_STRUCT_H_ */ 33 | -------------------------------------------------------------------------------- /nodelib/struct/Msg_Struct.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Msg_Struct.cpp 3 | * 4 | * Created on: Aug 2, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "V8_Base.h" 9 | #include "Struct_Manager.h" 10 | #include "Msg_Struct.h" 11 | 12 | Msg_Struct::Msg_Struct() : 13 | Base_Struct(), 14 | msg_id_(0), 15 | msg_name_() {} 16 | 17 | Msg_Struct::~Msg_Struct() { 18 | msg_id_ = 0; 19 | msg_name_.clear(); 20 | } 21 | 22 | int Msg_Struct::init(Xml &xml, TiXmlNode *node) { 23 | if(node) { 24 | msg_id_ = xml.get_attr_int(node, "msg_id"); 25 | msg_name_ = xml.get_attr_str(node, "msg_name"); 26 | } 27 | 28 | //Base_Struct初始化放在最后面,因为Base_Struct初始化内部会遍历node节点 29 | return Base_Struct::init(xml, node); 30 | } 31 | 32 | v8::Local Msg_Struct::build_json_msg_object(Isolate* isolate, const Msg_Head &msg_head, const Json::Value &value) { 33 | EscapableHandleScope handle_scope(isolate); 34 | 35 | Local context(isolate->GetCurrentContext()); 36 | v8::Local object = build_value_object(isolate, field_vec(), value); 37 | if(object.IsEmpty()) { 38 | return handle_scope.Escape(v8::Local()); 39 | } 40 | 41 | object->Set(context, String::NewFromUtf8(isolate, "cid", NewStringType::kNormal).ToLocalChecked(), 42 | Int32::New(isolate, msg_head.cid)).FromJust(); 43 | object->Set(context, String::NewFromUtf8(isolate, "msg_id", NewStringType::kNormal).ToLocalChecked(), 44 | Int32::New(isolate, msg_head.msg_id)).FromJust(); 45 | object->Set(context, String::NewFromUtf8(isolate, "msg_type", NewStringType::kNormal).ToLocalChecked(), 46 | Int32::New(isolate, msg_head.msg_type)).FromJust(); 47 | return handle_scope.Escape(object); 48 | } 49 | 50 | v8::Local Msg_Struct::build_buffer_msg_object(Isolate* isolate, const Msg_Head &msg_head, Bit_Buffer &buffer) { 51 | EscapableHandleScope handle_scope(isolate); 52 | 53 | Local context(isolate->GetCurrentContext()); 54 | v8::Local object = Object::New(isolate); 55 | build_bit_object(isolate, field_vec(), buffer, object); 56 | if(object.IsEmpty()) { 57 | return handle_scope.Escape(v8::Local()); 58 | } 59 | 60 | object->Set(context, String::NewFromUtf8(isolate, "cid", NewStringType::kNormal).ToLocalChecked(), 61 | Int32::New(isolate, msg_head.cid)).FromJust(); 62 | object->Set(context, String::NewFromUtf8(isolate, "msg_id", NewStringType::kNormal).ToLocalChecked(), 63 | Int32::New(isolate, msg_head.msg_id)).FromJust(); 64 | object->Set(context, String::NewFromUtf8(isolate, "msg_type", NewStringType::kNormal).ToLocalChecked(), 65 | Int32::New(isolate, msg_head.msg_type)).FromJust(); 66 | object->Set(context, String::NewFromUtf8(isolate, "sid", NewStringType::kNormal).ToLocalChecked(), 67 | Uint32::New(isolate, msg_head.sid)).FromJust(); 68 | return handle_scope.Escape(object); 69 | } 70 | -------------------------------------------------------------------------------- /nodelib/struct/Msg_Struct.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Msg_Struct.h 3 | * 4 | * Created on: Aug 2, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef MSG_STRUCT_H_ 9 | #define MSG_STRUCT_H_ 10 | 11 | #include "Base_Struct.h" 12 | 13 | class Msg_Struct: public Base_Struct { 14 | public: 15 | Msg_Struct(); 16 | virtual ~Msg_Struct(); 17 | 18 | virtual int init(Xml &xml, TiXmlNode *node); 19 | 20 | inline const int msg_id() { return msg_id_; } 21 | inline const std::string &msg_name() { return msg_name_; } 22 | 23 | //将Json::Value转成v8::object 24 | v8::Local build_json_msg_object(Isolate* isolate, const Msg_Head &msg_head, const Json::Value &value); 25 | //Bit_Buffer转成v8::object 26 | v8::Local build_buffer_msg_object(Isolate* isolate, const Msg_Head &msg_head, Bit_Buffer &buffer); 27 | 28 | private: 29 | int msg_id_; 30 | std::string msg_name_; 31 | }; 32 | 33 | #endif /* MSG_STRUCT_H_ */ 34 | -------------------------------------------------------------------------------- /nodelib/struct/Robot_Struct.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Robot_Struct.h 3 | * 4 | * Created on: Sep 27, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef ROBOT_STRUCT_H_ 9 | #define ROBOT_STRUCT_H_ 10 | 11 | #include "Base_Struct.h" 12 | 13 | class Robot_Struct: public Base_Struct { 14 | public: 15 | Robot_Struct(); 16 | virtual ~Robot_Struct(); 17 | 18 | virtual int init(Xml &xml, TiXmlNode *node); 19 | 20 | inline const int msg_id() { return msg_id_; } 21 | inline const std::string &msg_name() { return msg_name_; } 22 | 23 | //读写bit_buffer 24 | void write_bit_buffer(const Field_Vec &field_vec, Bit_Buffer &buffer); 25 | void read_bit_buffer(const Field_Vec &field_vec, Bit_Buffer &buffer); 26 | 27 | private: 28 | void write_bit_buffer_arg(const Field_Info &field_info, Bit_Buffer &buffer); 29 | void write_bit_buffer_vector(const Field_Info &field_info, Bit_Buffer &buffer); 30 | void write_bit_buffer_map(const Field_Info &field_info, Bit_Buffer &buffer); 31 | void write_bit_buffer_struct(const Field_Info &field_info, Bit_Buffer &buffer); 32 | 33 | void read_bit_buffer_arg(const Field_Info &field_info, Bit_Buffer &buffer); 34 | void read_bit_buffer_vector(const Field_Info &field_info, Bit_Buffer &buffer); 35 | void read_bit_buffer_map(const Field_Info &field_info, Bit_Buffer &buffer); 36 | void read_bit_buffer_struct(const Field_Info &field_info, Bit_Buffer &buffer); 37 | 38 | private: 39 | int msg_id_; 40 | std::string msg_name_; 41 | }; 42 | 43 | #endif /* ROBOT_STRUCT_H_ */ 44 | -------------------------------------------------------------------------------- /nodelib/struct/Struct_Manager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Struct_Manager.h 3 | * 4 | * Created on: Aug 4, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef STRUCT_MANAGER_H_ 9 | #define STRUCT_MANAGER_H_ 10 | 11 | #include 12 | #include "DB_Struct.h" 13 | #include "Msg_Struct.h" 14 | #include "Robot_Struct.h" 15 | 16 | class Struct_Manager { 17 | public: 18 | typedef std::unordered_map Struct_Name_Map; 19 | public: 20 | static Struct_Manager *instance(void); 21 | 22 | int init_struct(const char *file_path, int struct_type); 23 | 24 | Base_Struct *get_base_struct(const std::string &struct_name); 25 | Msg_Struct *get_msg_struct(const std::string &struct_name); 26 | Robot_Struct *get_robot_struct(const std::string &struct_name); 27 | DB_Struct *get_db_struct(const std::string &struct_name); 28 | 29 | inline const Struct_Name_Map &base_struct_name_map(void) { return base_struct_name_map_; } 30 | inline const Struct_Name_Map &msg_struct_name_map(void) { return msg_struct_name_map_; } 31 | inline const Struct_Name_Map &robot_struct_name_map(void) { return robot_struct_name_map_; } 32 | inline const Struct_Name_Map &db_struct_name_map(void) { return db_struct_name_map_; } 33 | 34 | inline void set_log_trace(bool log_trace) { log_trace_ = log_trace; } 35 | inline bool log_trace(void) { return log_trace_; } 36 | inline void set_agent_num(int agent_num) { agent_num_ = agent_num; } 37 | inline int agent_num() { return agent_num_; } 38 | inline void set_server_num(int server_num) { server_num_ = server_num; } 39 | inline int server_num() { return server_num_; } 40 | 41 | private: 42 | int load_struct(const char *file_path, int struct_type, Struct_Name_Map &struct_name_map); 43 | 44 | private: 45 | Struct_Manager(void); 46 | virtual ~Struct_Manager(void); 47 | Struct_Manager(const Struct_Manager &); 48 | const Struct_Manager &operator=(const Struct_Manager &); 49 | 50 | private: 51 | static Struct_Manager *instance_; 52 | 53 | bool log_trace_; //是否打印日志跟踪struct 54 | int agent_num_; //代理编号 55 | int server_num_; //服务器编号 56 | 57 | Struct_Name_Map base_struct_name_map_; 58 | Struct_Name_Map msg_struct_name_map_; 59 | Struct_Name_Map robot_struct_name_map_; 60 | Struct_Name_Map db_struct_name_map_; 61 | }; 62 | 63 | #define STRUCT_MANAGER Struct_Manager::instance() 64 | 65 | #endif /* STRUCT_MANAGER_H_ */ 66 | -------------------------------------------------------------------------------- /nodelib/struct/Struct_Tool.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Struct_Tool.h 3 | * Created on: Oct 29, 2016 4 | * Author: zhangyalei 5 | */ 6 | 7 | #ifndef STRUCT_TOOL_ 8 | #define STRUCT_TOOL_ 9 | 10 | #include 11 | #include 12 | #include "Base_Define.h" 13 | 14 | #define BEGIN_IMPLEMENT "\nfunction %s() {\n" 15 | #define END_IMPLEMENT "}\n" 16 | #define RESET_NUMBER "\tthis.%s = 0;\n" 17 | #define RESET_BOOL "\tthis.%s = false;\n" 18 | #define RESET_STRING "\tthis.%s = \"\";\n" 19 | #define RESET_VECTOR "\tthis.%s = new Array();\n" 20 | #define RESET_MAP "\tthis.%s = new Map();\n" 21 | #define RESET_STRUCT "\tthis.%s = new %s();\n" 22 | #define BEGIN_MESSAGE "if (typeof Msg == \"undefined\") {\n"\ 23 | "\tvar Msg = {};\n" 24 | #define MESSAGE_BODY "\tMsg.%s = %d;\n" 25 | #define END_MESSAGE END_IMPLEMENT 26 | 27 | #define SQL_HEAD "CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARACTER SET utf8;\n"\ 28 | "USE %s\n" 29 | #define TABLE_HEAD "\nDROP TABLE IF EXISTS `%s`;\n"\ 30 | "CREATE TABLE `%s` (\n" 31 | #define TABLE_END ")ENGINE=InnoDB DEFAULT CHARSET=utf8;\n" 32 | #define SQL_INT_11 "\t%s int(11) NOT NULL default '0',\n" 33 | #define SQL_INT_2 "\t%s int(2) NOT NULL default '0',\n" 34 | #define SQL_BIGINT "\t%s bigint(20) NOT NULL default '0',\n" 35 | #define SQL_VARCHAR "\t%s varchar(120) NOT NULL default '',\n" 36 | #define SQL_TEXT "\t%s text NOT NULL,\n" 37 | #define PRIMARY_KEY "\tPRIMARY KEY (%s)\n" 38 | 39 | class Struct_Tool { 40 | typedef std::unordered_set Field_Name_Set; 41 | typedef std::vector Field_Define_Vec; 42 | public: 43 | Struct_Tool(); 44 | ~Struct_Tool(); 45 | int write_struct(); 46 | 47 | private: 48 | int write_to_struct(); 49 | int write_field_struct(const Field_Vec &field_vec); 50 | int write_to_message(); 51 | int write_to_sql(); 52 | 53 | private: 54 | //将结构体名字存在set,防止if/switch相同结构体重复生成 55 | Field_Name_Set field_name_set; 56 | Field_Define_Vec field_define_vec; 57 | }; 58 | 59 | #endif 60 | -------------------------------------------------------------------------------- /nodelib/v8/V8_Base.h: -------------------------------------------------------------------------------- 1 | /* 2 | * V8_Base.h 3 | * 4 | * Created on: Oct 21, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef V8_BASE_H_ 9 | #define V8_BASE_H_ 10 | 11 | #include 12 | #include "Xml.h" 13 | #include "include/v8.h" 14 | 15 | using namespace v8; 16 | 17 | std::string get_struct_name(int msg_type, int msg_id); 18 | std::string to_string(const String::Utf8Value& value); 19 | int run_script(Isolate* isolate, const char* file_path); 20 | MaybeLocal read_file(Isolate* isolate, const char* file_path); 21 | void report_exception(Isolate* isolate, TryCatch* handler, const char* file_path); 22 | std::string get_stack_trace(Isolate* isolate); 23 | 24 | //函数说明:获取系统proc信息 参数:无 返回值:proc信息对象 25 | void get_proc_info(const FunctionCallbackInfo& args); 26 | //函数说明:获取v8堆信息 参数:无 返回值:堆信息对象 27 | void get_heap_info(const FunctionCallbackInfo& args); 28 | 29 | //函数说明:引用js文件 参数:1.文件路径 返回值:无 30 | void require(const FunctionCallbackInfo& args); 31 | //函数说明:读取json配置文件 参数:1.文件路径 返回值:文件内容字符串对象 32 | void read_json(const FunctionCallbackInfo& args); 33 | //函数说明:读取xml配置文件 参数:1.文件路径 返回值:文件内容字符串对象 34 | void read_xml(const FunctionCallbackInfo& args); 35 | void read_xml_data(Isolate *isolate, Xml &xml, TiXmlNode *node, Local &object); 36 | //函数说明:hash运算 参数:进行hash运算的字符串 返回值:hash值 37 | void hash(const FunctionCallbackInfo& args); 38 | //函数说明:生成token 参数:1.帐号名 返回值:token 39 | void generate_token(const FunctionCallbackInfo& args); 40 | 41 | //函数说明:打印程序调试信息 参数:可变参数列表 返回值:无 42 | void log_debug(const FunctionCallbackInfo& args); 43 | //函数说明:打印程序运行信息 参数:可变参数列表 返回值:无 44 | void log_info(const FunctionCallbackInfo& args); 45 | //函数说明:打印程序警告信息 参数:可变参数列表 返回值:无 46 | void log_warn(const FunctionCallbackInfo& args); 47 | //函数说明:打印程序错误信息 参数:可变参数列表 返回值:无 48 | void log_error(const FunctionCallbackInfo& args); 49 | //函数说明:打印程序运行堆栈 参数:可变参数列表 返回值:无 50 | void log_trace(const FunctionCallbackInfo& args); 51 | 52 | #endif /* V8_BASE_H_ */ 53 | -------------------------------------------------------------------------------- /nodelib/v8/V8_Wrap.h: -------------------------------------------------------------------------------- 1 | /* 2 | * V8_Wrap.h 3 | * 4 | * Created on: Feb 1, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef V8_WRAP_H_ 9 | #define V8_WRAP_H_ 10 | 11 | #include "include/v8.h" 12 | using namespace v8; 13 | 14 | //创建v8运行环境 15 | Local create_context(Isolate* isolate); 16 | ////函数说明:创建进程 参数:1.node_type 2.node_id 3.endpoint_gid 4.node_name 返回值:无 17 | void fork_process(const FunctionCallbackInfo& args); 18 | //函数说明:获取node v8堆栈 参数:1.node_type 2.endpoint_id 返回值:无 19 | void get_node_stack(const FunctionCallbackInfo& args); 20 | //函数说明:获取node状态信息 参数:无 返回值:node状态对象 21 | void get_node_status(const FunctionCallbackInfo& args); 22 | //函数说明:注册定时器到c++层 参数:1.定时器id 2.定时器间隔(毫秒单位) 3.从注册定时器到下次定时器到期中间间隔秒数 返回值:无 23 | void register_timer(const FunctionCallbackInfo& args); 24 | //函数说明:发送消息object 参数:1.eid 2.cid 3.msg_id 4.msg_type 5.sid 6.消息object 返回值:无 25 | void send_msg(const FunctionCallbackInfo& args); 26 | //函数说明:关闭客户端连接 参数:1.eid 2.drop_cid 返回值:无 27 | void close_client(const FunctionCallbackInfo& args); 28 | 29 | #endif /* V8_WRAP_H_ */ 30 | -------------------------------------------------------------------------------- /nodelib/xml/Xml.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/nodelib/xml/Xml.cpp -------------------------------------------------------------------------------- /nodelib/xml/Xml.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/nodelib/xml/Xml.h -------------------------------------------------------------------------------- /nodelib/xml/tinystr.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | www.sourceforge.net/projects/tinyxml 3 | 4 | This software is provided 'as-is', without any express or implied 5 | warranty. In no event will the authors be held liable for any 6 | damages arising from the use of this software. 7 | 8 | Permission is granted to anyone to use this software for any 9 | purpose, including commercial applications, and to alter it and 10 | redistribute it freely, subject to the following restrictions: 11 | 12 | 1. The origin of this software must not be misrepresented; you must 13 | not claim that you wrote the original software. If you use this 14 | software in a product, an acknowledgment in the product documentation 15 | would be appreciated but is not required. 16 | 17 | 2. Altered source versions must be plainly marked as such, and 18 | must not be misrepresented as being the original software. 19 | 20 | 3. This notice may not be removed or altered from any source 21 | distribution. 22 | */ 23 | 24 | 25 | #ifndef TIXML_USE_STL 26 | 27 | #include "tinystr.h" 28 | 29 | // Error value for find primitive 30 | const TiXmlString::size_type TiXmlString::npos = static_cast< TiXmlString::size_type >(-1); 31 | 32 | 33 | // Null rep. 34 | TiXmlString::Rep TiXmlString::nullrep_ = { 0, 0, { '\0' } }; 35 | 36 | 37 | void TiXmlString::reserve (size_type cap) 38 | { 39 | if (cap > capacity()) 40 | { 41 | TiXmlString tmp; 42 | tmp.init(length(), cap); 43 | memcpy(tmp.start(), data(), length()); 44 | swap(tmp); 45 | } 46 | } 47 | 48 | 49 | TiXmlString& TiXmlString::assign(const char* str, size_type len) 50 | { 51 | size_type cap = capacity(); 52 | if (len > cap || cap > 3*(len + 8)) 53 | { 54 | TiXmlString tmp; 55 | tmp.init(len); 56 | memcpy(tmp.start(), str, len); 57 | swap(tmp); 58 | } 59 | else 60 | { 61 | memmove(start(), str, len); 62 | set_size(len); 63 | } 64 | return *this; 65 | } 66 | 67 | 68 | TiXmlString& TiXmlString::append(const char* str, size_type len) 69 | { 70 | size_type newsize = length() + len; 71 | if (newsize > capacity()) 72 | { 73 | reserve (newsize + capacity()); 74 | } 75 | memmove(finish(), str, len); 76 | set_size(newsize); 77 | return *this; 78 | } 79 | 80 | 81 | TiXmlString operator + (const TiXmlString & a, const TiXmlString & b) 82 | { 83 | TiXmlString tmp; 84 | tmp.reserve(a.length() + b.length()); 85 | tmp += a; 86 | tmp += b; 87 | return tmp; 88 | } 89 | 90 | TiXmlString operator + (const TiXmlString & a, const char* b) 91 | { 92 | TiXmlString tmp; 93 | TiXmlString::size_type b_len = static_cast( strlen(b) ); 94 | tmp.reserve(a.length() + b_len); 95 | tmp += a; 96 | tmp.append(b, b_len); 97 | return tmp; 98 | } 99 | 100 | TiXmlString operator + (const char* a, const TiXmlString & b) 101 | { 102 | TiXmlString tmp; 103 | TiXmlString::size_type a_len = static_cast( strlen(a) ); 104 | tmp.reserve(a_len + b.length()); 105 | tmp.append(a, a_len); 106 | tmp += b; 107 | return tmp; 108 | } 109 | 110 | 111 | #endif // TIXML_USE_STL 112 | -------------------------------------------------------------------------------- /nodelib/xml/tinyxmlerror.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | www.sourceforge.net/projects/tinyxml 3 | Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com) 4 | 5 | This software is provided 'as-is', without any express or implied 6 | warranty. In no event will the authors be held liable for any 7 | damages arising from the use of this software. 8 | 9 | Permission is granted to anyone to use this software for any 10 | purpose, including commercial applications, and to alter it and 11 | redistribute it freely, subject to the following restrictions: 12 | 13 | 1. The origin of this software must not be misrepresented; you must 14 | not claim that you wrote the original software. If you use this 15 | software in a product, an acknowledgment in the product documentation 16 | would be appreciated but is not required. 17 | 18 | 2. Altered source versions must be plainly marked as such, and 19 | must not be misrepresented as being the original software. 20 | 21 | 3. This notice may not be removed or altered from any source 22 | distribution. 23 | */ 24 | 25 | #include "tinyxml.h" 26 | 27 | // The goal of the seperate error file is to make the first 28 | // step towards localization. tinyxml (currently) only supports 29 | // english error messages, but the could now be translated. 30 | // 31 | // It also cleans up the code a bit. 32 | // 33 | 34 | const char* TiXmlBase::errorString[ TiXmlBase::TIXML_ERROR_STRING_COUNT ] = 35 | { 36 | "No error", 37 | "Error", 38 | "Failed to open file", 39 | "Error parsing Element.", 40 | "Failed to read Element name", 41 | "Error reading Element value.", 42 | "Error reading Attributes.", 43 | "Error: empty tag.", 44 | "Error reading end tag.", 45 | "Error parsing Unknown.", 46 | "Error parsing Comment.", 47 | "Error parsing Declaration.", 48 | "Error document empty.", 49 | "Error null (0) or unexpected EOF found in input stream.", 50 | "Error parsing CDATA.", 51 | "Error when TiXmlDocument added to document, because TiXmlDocument can only be at the root.", 52 | }; 53 | -------------------------------------------------------------------------------- /plugin/aoi/Aoi_Entity.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Created on: Aug 11, 2016 3 | * Author: lijunliang 4 | */ 5 | 6 | #include "Aoi_Entity.h" 7 | #include "Aoi_Manager.h" 8 | 9 | Aoi_Entity::Aoi_Entity(): 10 | sid_(0), 11 | eid_(0), 12 | aoi_manager_(nullptr), 13 | pos_(0,0,0), 14 | opos_(0,0,0), 15 | radius_(0), 16 | x_pos_(), 17 | y_pos_(), 18 | enter_map_(), 19 | leave_map_(), 20 | aoi_map_() 21 | { 22 | 23 | } 24 | 25 | Aoi_Entity::~Aoi_Entity() { 26 | 27 | } 28 | 29 | Aoi_Entity_Pool Aoi_Entity::aoi_entity_pool_; 30 | 31 | Aoi_Entity *Aoi_Entity::create_aoi_entity(int sid, int eid, int radius) { 32 | Aoi_Entity *aoi_entity = aoi_entity_pool_.pop(); 33 | aoi_entity->sid(sid); 34 | aoi_entity->eid(eid); 35 | aoi_entity->radius(radius); 36 | return aoi_entity; 37 | } 38 | 39 | void Aoi_Entity::reclaim_aoi_entity(Aoi_Entity *entity) { 40 | entity->reset(); 41 | aoi_entity_pool_.push(entity); 42 | } 43 | 44 | void Aoi_Entity::add_aoi_entity(Aoi_Entity *entity) { 45 | if(aoi_map_.find(entity->sid()) != aoi_map_.end()) 46 | return; 47 | aoi_map_[entity->sid()] = entity; 48 | } 49 | 50 | void Aoi_Entity::del_aoi_entity(Aoi_Entity *entity) { 51 | if(aoi_map_.find(entity->sid()) == aoi_map_.end()) 52 | return; 53 | aoi_map_.erase(entity->sid()); 54 | } 55 | 56 | void Aoi_Entity::update_aoi_map(AOI_MAP &new_map) { 57 | enter_map_.clear(); 58 | leave_map_.clear(); 59 | for(AOI_MAP::iterator iter = aoi_map_.begin(); 60 | iter != aoi_map_.end(); iter++){ 61 | if(new_map.find(iter->second->sid()) == new_map.end()){ 62 | iter->second->del_aoi_entity(this); 63 | leave_map_[iter->second->sid()] = iter->second; 64 | } 65 | } 66 | for(AOI_MAP::iterator iter = new_map.begin(); 67 | iter != new_map.end(); iter++){ 68 | if(aoi_map_.find(iter->second->sid()) == aoi_map_.end()){ 69 | iter->second->add_aoi_entity(this); 70 | enter_map_[iter->second->sid()] = iter->second; 71 | } 72 | } 73 | aoi_map_.clear(); 74 | for(AOI_MAP::iterator iter = new_map.begin(); 75 | iter != new_map.end(); iter++){ 76 | add_aoi_entity(iter->second); 77 | } 78 | } 79 | 80 | void Aoi_Entity::clear_aoi_map() { 81 | for(AOI_MAP::iterator iter = aoi_map_.begin(); iter != aoi_map_.end(); iter++){ 82 | iter->second->del_aoi_entity(this); 83 | } 84 | enter_map_.clear(); 85 | leave_map_.clear(); 86 | aoi_map_.clear(); 87 | } 88 | 89 | void Aoi_Entity::reset() { 90 | sid_ = 0; 91 | eid_ = 0; 92 | aoi_manager_ = nullptr; 93 | pos_ = Position(0,0,0); 94 | opos_ = Position(0,0,0); 95 | radius_ = 0; 96 | enter_map_.clear(); 97 | leave_map_.clear(); 98 | aoi_map_.clear(); 99 | } 100 | -------------------------------------------------------------------------------- /plugin/aoi/Aoi_Entity.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Created on: Aug 11, 2016 3 | * Author: lijunliang 4 | */ 5 | 6 | #ifndef AOI_ENTITY_H_ 7 | #define AOI_ENTITY_H_ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "Base_Struct.h" 15 | #include "Object_Pool.h" 16 | 17 | class Aoi_Entity; 18 | class Aoi_Manager; 19 | 20 | struct Position { 21 | int x; 22 | int y; 23 | int z; 24 | Position(int x1, int y1, int z1) { 25 | x = x1; 26 | y = y1; 27 | z = z1; 28 | } 29 | void operator = (Position pos) { 30 | x = pos.x; 31 | y = pos.y; 32 | z = pos.z; 33 | } 34 | }; 35 | 36 | typedef std::list AOI_LIST; 37 | typedef std::unordered_map AOI_MAP; 38 | typedef Object_Pool Aoi_Entity_Pool; 39 | 40 | class Aoi_Entity { 41 | public: 42 | static Aoi_Entity *create_aoi_entity(int sid, int eid, int radius); 43 | static void reclaim_aoi_entity(Aoi_Entity *entity); 44 | public: 45 | Aoi_Entity(); 46 | ~Aoi_Entity(); 47 | void update_aoi_map(AOI_MAP &new_map); 48 | void add_aoi_entity(Aoi_Entity *entity); 49 | void del_aoi_entity(Aoi_Entity *entity); 50 | void clear_aoi_map(); 51 | void reset(); 52 | 53 | inline int sid(){return sid_;} 54 | inline void sid(int sid){sid_ = sid;} 55 | inline int eid(){return eid_;} 56 | inline void eid(int eid){eid_ = eid;} 57 | inline int radius(){return radius_;} 58 | inline void radius(int radius){radius_ = radius;} 59 | inline void aoi_manager(Aoi_Manager *manager){aoi_manager_ = manager;} 60 | inline Aoi_Manager *aoi_manager(){return aoi_manager_;} 61 | inline Position &pos(){return pos_;} 62 | inline Position &opos(){return opos_;} 63 | 64 | inline void x_pos(AOI_LIST::iterator iter){x_pos_ = iter;} 65 | inline void y_pos(AOI_LIST::iterator iter){y_pos_ = iter;} 66 | inline AOI_LIST::iterator x_pos(){return x_pos_;} 67 | inline AOI_LIST::iterator y_pos(){return y_pos_;} 68 | inline AOI_MAP &enter_map(){return enter_map_;} 69 | inline AOI_MAP &leave_map(){return leave_map_;} 70 | inline AOI_MAP &aoi_map(){return aoi_map_;} 71 | private: 72 | static Aoi_Entity_Pool aoi_entity_pool_; 73 | private: 74 | int sid_; 75 | int eid_; 76 | Aoi_Manager *aoi_manager_; 77 | Position pos_; 78 | Position opos_; 79 | int radius_; 80 | AOI_LIST::iterator x_pos_; 81 | AOI_LIST::iterator y_pos_; 82 | AOI_MAP enter_map_; 83 | AOI_MAP leave_map_; 84 | AOI_MAP aoi_map_; 85 | }; 86 | 87 | #endif 88 | -------------------------------------------------------------------------------- /plugin/aoi/Aoi_Manager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Created on: Aug 10, 2016 3 | * Author: lijunliang 4 | */ 5 | 6 | #ifndef AOI_MANAGER_H_ 7 | #define AOI_MANAGER_H_ 8 | 9 | #include "Object_Pool.h" 10 | #include "Aoi_Entity.h" 11 | 12 | class Aoi_Manager; 13 | typedef std::unordered_map AOI_MANAGER_MAP; 14 | typedef std::unordered_map AOI_ENTITY_MAP; 15 | 16 | class Aoi_Manager { 17 | public: 18 | static bool create_aoi_manager(int id); 19 | static Aoi_Manager *get_aoi_manager(int id); 20 | static Aoi_Entity *find_entity(int sid); 21 | static void add_entity(Aoi_Entity *entity); 22 | static void rmv_entity(Aoi_Entity *entity); 23 | public: 24 | Aoi_Manager(int id); 25 | ~Aoi_Manager(); 26 | int on_enter_aoi(Aoi_Entity *entity); 27 | int on_update_aoi(Aoi_Entity *entity); 28 | int on_leave_aoi(Aoi_Entity *entity); 29 | 30 | private: 31 | void insert_entity(Aoi_Entity *entity); 32 | void update_list(Aoi_Entity *entity, bool direct, int xy); 33 | void update_aoi_map(Aoi_Entity *entity); 34 | void print_list(AOI_LIST list); 35 | private: 36 | static AOI_MANAGER_MAP aoi_manager_map_; 37 | static AOI_ENTITY_MAP aoi_entity_map_; 38 | private: 39 | int mgr_id_; 40 | AOI_LIST x_list_; 41 | AOI_LIST y_list_; 42 | }; 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /plugin/aoi/Aoi_Wrap.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Aoi_Wrap.h 3 | * 4 | * Created on: Sep 3, 2016 5 | * Author: lijunliang 6 | */ 7 | 8 | #ifndef AOI_WRAP_H_ 9 | #define AOI_WRAP_H_ 10 | 11 | #include "include/v8.h" 12 | 13 | using namespace v8; 14 | 15 | void create_aoi_manager(const FunctionCallbackInfo& args); 16 | void create_aoi_entity(const FunctionCallbackInfo& args); 17 | 18 | void enter_aoi(const FunctionCallbackInfo& args); 19 | void update_position(const FunctionCallbackInfo& args); 20 | void leave_aoi(const FunctionCallbackInfo& args); 21 | void get_aoi_list(const FunctionCallbackInfo& args); 22 | void send_msg_list(const FunctionCallbackInfo& args); 23 | void broadcast_msg_to_all(const FunctionCallbackInfo& args); 24 | void broadcast_msg_to_all_without_self(const FunctionCallbackInfo& args); 25 | void reclaim_aoi_entity(const FunctionCallbackInfo& args); 26 | void broadcast_msg_sub(const FunctionCallbackInfo& args, bool with_self); 27 | 28 | #endif /* AOI_WRAP_H_ */ 29 | -------------------------------------------------------------------------------- /plugin/aoi/Makefile: -------------------------------------------------------------------------------- 1 | ############################################################################## 2 | # # 3 | # 默认为release模式编译,debug模式请使用参数'MODE=DEBUG' # 4 | # # 5 | ############################################################################## 6 | 7 | ###在这里添加源文件目录### 8 | SRCDIR= ./\ 9 | 10 | ###这里定义目标文件目录### 11 | OBJDIR =../../.obj/scene_obj/ 12 | 13 | TARGET_NAME=aoiplugin.so 14 | 15 | BIN=../ 16 | 17 | INCLUDE=-I/usr/local/include/nodelib/base\ 18 | -I/usr/local/include/nodelib/network\ 19 | -I/usr/local/include/nodelib/node\ 20 | -I/usr/local/include/nodelib/struct\ 21 | -I/usr/local/include/nodelib/v8\ 22 | -I/usr/local/include/nodelib/xml\ 23 | $(addprefix -I, $(SRCDIR)) 24 | 25 | LIBDIR=-L./ 26 | 27 | LIB=-lv8\ 28 | -lv8_libplatform\ 29 | 30 | CC=g++ 31 | 32 | DEPENDS=-MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" 33 | 34 | ifeq ($(MODE), DEBUG) 35 | BUILD_FLAG = -O0 -g3 36 | else 37 | BUILD_FLAG = -O3 38 | endif 39 | 40 | CONDITION= 41 | 42 | COM_FLAG=-Wall -c -fmessage-length=0 -std=c++11 -fPIC 43 | 44 | LDFLAG=-shared 45 | 46 | BIN_TARGET=$(OBJDIR)bin/$(TARGET_NAME) 47 | 48 | SRCS=$(wildcard $(addsuffix *.cpp, $(SRCDIR))) 49 | 50 | OBJECTS:=$(addprefix $(OBJDIR), $(subst ./,,$(SRCS:.cpp=.o))) 51 | 52 | .PHONY:all mkobjdir clean config 53 | 54 | all:mkobjdir $(BIN_TARGET) 55 | 56 | -include $(OBJECTS:.o=.d) 57 | 58 | $(BIN_TARGET):$(OBJECTS) 59 | @echo "Linking target $@" 60 | $(CC) $(LDFLAG) -o $@ $^ $(LIBDIR) $(LIB) 61 | @echo " " 62 | @echo "Finished building target: $(TARGET_NAME)" 63 | @echo " " 64 | @-cp -f $(BIN_TARGET) $(BIN) 65 | 66 | $(OBJDIR)%.o:%.cpp 67 | ifeq ($(MODE), DEBUG) 68 | @echo "Building DEBUG MODE target $@" 69 | else 70 | @echo "Building RELEASE MODE target $@" 71 | endif 72 | $(CC) $(INCLUDE) $(BUILD_FLAG) $(COM_FLAG) $(DEPENDS) $(CONDITION) -o "$(@)" "$(<)" 73 | @echo " " 74 | 75 | mkobjdir: 76 | @test -d $(OBJDIR) || (mkdir $(OBJDIR) && mkdir $(OBJDIR)bin $(addprefix $(OBJDIR), $(subst ./,,$(SRCDIR)))) 77 | 78 | clean: 79 | -rm -rf $(OBJDIR) 80 | -------------------------------------------------------------------------------- /plugin/aoi/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * main.cpp 3 | * 4 | * Created on: Dec 7, 2016 5 | * Author: lijunliang 6 | */ 7 | 8 | #include "Node_Manager.h" 9 | #include "Aoi_Wrap.h" 10 | 11 | using namespace v8; 12 | 13 | Global _g_aoi_entity_template; 14 | 15 | extern "C" { 16 | void init(Local &global, Isolate *isolate) { 17 | global->Set(String::NewFromUtf8(isolate, "create_aoi_entity", NewStringType::kNormal).ToLocalChecked(), 18 | FunctionTemplate::New(isolate, create_aoi_entity)); 19 | global->Set(String::NewFromUtf8(isolate, "create_aoi_manager", NewStringType::kNormal).ToLocalChecked(), 20 | FunctionTemplate::New(isolate, create_aoi_manager)); 21 | 22 | Local aoi_entity_template = ObjectTemplate::New(isolate); 23 | aoi_entity_template->SetInternalFieldCount(1); 24 | 25 | aoi_entity_template->Set(String::NewFromUtf8(isolate, "enter_aoi", NewStringType::kNormal).ToLocalChecked(), 26 | FunctionTemplate::New(isolate, enter_aoi)); 27 | aoi_entity_template->Set(String::NewFromUtf8(isolate, "leave_aoi", NewStringType::kNormal).ToLocalChecked(), 28 | FunctionTemplate::New(isolate, leave_aoi)); 29 | aoi_entity_template->Set(String::NewFromUtf8(isolate, "update_position", NewStringType::kNormal).ToLocalChecked(), 30 | FunctionTemplate::New(isolate, update_position)); 31 | aoi_entity_template->Set(String::NewFromUtf8(isolate, "get_aoi_list", NewStringType::kNormal).ToLocalChecked(), 32 | FunctionTemplate::New(isolate, get_aoi_list)); 33 | aoi_entity_template->Set(String::NewFromUtf8(isolate, "send_msg_list", NewStringType::kNormal).ToLocalChecked(), 34 | FunctionTemplate::New(isolate, send_msg_list)); 35 | aoi_entity_template->Set(String::NewFromUtf8(isolate, "broadcast_msg_to_all", NewStringType::kNormal).ToLocalChecked(), 36 | FunctionTemplate::New(isolate, broadcast_msg_to_all)); 37 | aoi_entity_template->Set(String::NewFromUtf8(isolate, "broadcast_msg_to_all_without_self", NewStringType::kNormal).ToLocalChecked(), 38 | FunctionTemplate::New(isolate, broadcast_msg_to_all_without_self)); 39 | aoi_entity_template->Set(String::NewFromUtf8(isolate, "reclaim", NewStringType::kNormal).ToLocalChecked(), 40 | FunctionTemplate::New(isolate, reclaim_aoi_entity)); 41 | _g_aoi_entity_template.Reset(isolate, aoi_entity_template); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /plugin/db/DB_Manager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * DB_Manager.h 3 | * 4 | * Created on: Nov 9, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef DB_MANAGER_H_ 9 | #define DB_MANAGER_H_ 10 | 11 | #include 12 | #include 13 | #include "Bit_Buffer.h" 14 | #include "Buffer_List.h" 15 | #include "Object_Pool.h" 16 | #include "List.h" 17 | #include "Thread.h" 18 | #include "Node_Define.h" 19 | 20 | enum Enpoint_Gid { 21 | GID_DATA_SERVER = 1, 22 | GID_DATA_CONNECTOR = 2, 23 | }; 24 | 25 | enum Msg_Id { 26 | SYNC_NODE_INFO = 1, 27 | SYNC_DB_RET_CODE = 244, 28 | SYNC_SELECT_DB_DATA = 245, 29 | SYNC_RES_SELECT_DB_DATA = 246, 30 | SYNC_GENERATE_ID = 247, 31 | SYNC_RES_GENERATE_ID = 248, 32 | SYNC_LOAD_DB_DATA = 249, 33 | SYNC_SAVE_DB_DATA = 250, 34 | SYNC_DELETE_DB_DATA = 251, 35 | SYNC_LOAD_RUNTIME_DATA = 252, 36 | SYNC_SAVE_RUNTIME_DATA = 253, 37 | SYNC_DELETE_RUNTIME_DATA = 254, 38 | SYNC_NODE_CODE = 255, 39 | }; 40 | 41 | class DB_Manager: public Thread { 42 | typedef Buffer_List Data_List; 43 | typedef List Int_List; 44 | typedef std::unordered_map Idx_Value_Map; 45 | typedef std::unordered_map Session_Map; 46 | typedef std::unordered_set UInt_Set; 47 | typedef std::vector Int_Vec; 48 | public: 49 | static DB_Manager *instance(void); 50 | 51 | int init(const Node_Info &node_info); 52 | virtual void run_handler(void); 53 | virtual int process_list(void); 54 | int tick(int tick_time); 55 | 56 | inline void push_buffer(Byte_Buffer *buffer) { 57 | notify_lock_.lock(); 58 | buffer_list_.push_back(buffer); 59 | notify_lock_.signal(); 60 | notify_lock_.unlock(); 61 | } 62 | inline void push_tick(int tick_time) { 63 | notify_lock_.lock(); 64 | tick_list_.push_back(tick_time); 65 | notify_lock_.signal(); 66 | notify_lock_.unlock(); 67 | } 68 | 69 | private: 70 | DB_Manager(void); 71 | virtual ~DB_Manager(void); 72 | DB_Manager(const DB_Manager &); 73 | const DB_Manager &operator=(const DB_Manager &); 74 | 75 | private: 76 | //根据条件查询db接口 77 | void select_db_data(Msg_Head &msg_head, Bit_Buffer &buffer); 78 | void generate_id(Msg_Head &msg_head, Bit_Buffer &buffer); 79 | 80 | //db数据操作接口 81 | void load_db_data(Msg_Head &msg_head, Bit_Buffer &buffer); 82 | void save_db_data(Msg_Head &msg_head, Bit_Buffer &buffer); 83 | void delete_db_data(Msg_Head &msg_head, Bit_Buffer &buffer); 84 | 85 | //运行时数据操作接口 86 | void load_runtime_data(Msg_Head &msg_head, Bit_Buffer &buffer); 87 | void save_runtime_data(Msg_Head &msg_head, Bit_Buffer &buffer); 88 | void delete_runtime_data(Msg_Head &msg_head, Bit_Buffer &buffer); 89 | 90 | //构造返回buffer 91 | void build_ret_buffer(Bit_Buffer &buffer, uint8_t opt_msg_id, int8_t ret, std::string struct_name, std::string query_name, int64_t key_index) { 92 | buffer.write_uint(opt_msg_id, 8); 93 | buffer.write_int(ret, 8); 94 | buffer.write_str(struct_name.c_str()); 95 | buffer.write_str(query_name.c_str()); 96 | buffer.write_int64(key_index); 97 | } 98 | 99 | private: 100 | static DB_Manager *instance_; 101 | 102 | Idx_Value_Map idx_value_map_; //存放idx值信息map 103 | int save_idx_tick_; //保存idx表tick时间 104 | int db_id_; //数据库id 105 | std::string struct_name_; //idx表结构体名称 106 | 107 | Data_List buffer_list_; //消息列表 108 | Int_List tick_list_; //定时器tick列表 109 | 110 | Node_Info node_info_; //节点信息 111 | Session_Map session_map_; //转发到connector进程session信息 112 | UInt_Set sid_set_; //本进程sid列表 113 | int data_node_idx_; //data链接器id索引 114 | int data_connector_size_; //data链接器数量 115 | Int_Vec data_connector_list_; //data链接器cid列表 116 | UInt_Set data_fork_list_; //data进程启动列表 117 | }; 118 | 119 | #define DB_MANAGER DB_Manager::instance() 120 | 121 | #endif /* DB_MANAGER_H_ */ 122 | -------------------------------------------------------------------------------- /plugin/db/Makefile: -------------------------------------------------------------------------------- 1 | ############################################################################## 2 | # # 3 | # 默认为release模式编译,debug模式请使用参数'MODE=DEBUG' # 4 | # # 5 | ############################################################################## 6 | 7 | ###在这里添加源文件目录### 8 | SRCDIR= ./\ 9 | 10 | ###这里定义目标文件目录### 11 | OBJDIR =../../.obj/db_obj/ 12 | 13 | TARGET_NAME=dbplugin.so 14 | 15 | BIN=../ 16 | 17 | INCLUDE=-I/usr/local/include/nodelib/base\ 18 | -I/usr/local/include/nodelib/db\ 19 | -I/usr/local/include/nodelib/network\ 20 | -I/usr/local/include/nodelib/node\ 21 | -I/usr/local/include/nodelib/struct\ 22 | -I/usr/local/include/nodelib/v8\ 23 | -I/usr/local/include/nodelib/xml\ 24 | $(addprefix -I, $(SRCDIR)) 25 | 26 | LIBDIR=-L./ 27 | 28 | LIB=-lv8\ 29 | -lv8_libplatform\ 30 | -lmysqlcppconn\ 31 | 32 | CC=g++ 33 | 34 | DEPENDS=-MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" 35 | 36 | ifeq ($(MODE), DEBUG) 37 | BUILD_FLAG = -O0 -g3 38 | else 39 | BUILD_FLAG = -O3 40 | endif 41 | 42 | CONDITION= 43 | 44 | COM_FLAG=-Wall -c -fmessage-length=0 -std=c++11 -fPIC 45 | 46 | LDFLAG=-shared 47 | 48 | BIN_TARGET=$(OBJDIR)bin/$(TARGET_NAME) 49 | 50 | SRCS=$(wildcard $(addsuffix *.cpp, $(SRCDIR))) 51 | 52 | OBJECTS:=$(addprefix $(OBJDIR), $(subst ./,,$(SRCS:.cpp=.o))) 53 | 54 | .PHONY:all mkobjdir clean config 55 | 56 | all:mkobjdir $(BIN_TARGET) 57 | 58 | -include $(OBJECTS:.o=.d) 59 | 60 | $(BIN_TARGET):$(OBJECTS) 61 | @echo "Linking target $@" 62 | $(CC) $(LDFLAG) -o $@ $^ $(LIBDIR) $(LIB) 63 | @echo " " 64 | @echo "Finished building target: $(TARGET_NAME)" 65 | @echo " " 66 | @-cp -f $(BIN_TARGET) $(BIN) 67 | 68 | $(OBJDIR)%.o:%.cpp 69 | ifeq ($(MODE), DEBUG) 70 | @echo "Building DEBUG MODE target $@" 71 | else 72 | @echo "Building RELEASE MODE target $@" 73 | endif 74 | $(CC) $(INCLUDE) $(BUILD_FLAG) $(COM_FLAG) $(DEPENDS) $(CONDITION) -o "$(@)" "$(<)" 75 | @echo " " 76 | 77 | mkobjdir: 78 | @test -d $(OBJDIR) || (mkdir $(OBJDIR) && mkdir $(OBJDIR)bin $(addprefix $(OBJDIR), $(subst ./,,$(SRCDIR)))) 79 | 80 | clean: 81 | -rm -rf $(OBJDIR) 82 | -------------------------------------------------------------------------------- /plugin/db/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * main.cpp 3 | * 4 | * Created on: Nov 1, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "include/v8.h" 9 | #include "Data_Manager.h" 10 | #include "DB_Manager.h" 11 | 12 | using namespace v8; 13 | 14 | extern "C" { 15 | void init(Local &global, Isolate *isolate) {} 16 | 17 | void create_thread(const Node_Info &node_info) { 18 | DATA_MANAGER->init_db_operator(); 19 | DB_MANAGER->init(node_info); 20 | DB_MANAGER->thr_create(); 21 | } 22 | 23 | void push_buffer(Byte_Buffer *buffer) { 24 | DB_MANAGER->push_buffer(buffer); 25 | } 26 | 27 | void push_tick(int tick_time) { 28 | DB_MANAGER->push_tick(tick_time); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /plugin/gate/Gate_Manager.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Gate_Manager.cpp 3 | * 4 | * Created on: Nov 8, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "Base_Function.h" 9 | #include "Node_Manager.h" 10 | #include "Gate_Manager.h" 11 | 12 | Gate_Manager::Gate_Manager(void): 13 | cid_session_map_(10000), 14 | sid_session_map_(10000) { } 15 | 16 | Gate_Manager::~Gate_Manager(void) { } 17 | 18 | Gate_Manager *Gate_Manager::instance_; 19 | 20 | Gate_Manager *Gate_Manager::instance(void) { 21 | if (instance_ == 0) 22 | instance_ = new Gate_Manager; 23 | return instance_; 24 | } 25 | 26 | void Gate_Manager::run_handler(void) { 27 | process_list(); 28 | } 29 | 30 | int Gate_Manager::process_list(void) { 31 | Msg_Head msg_head; 32 | Byte_Buffer *buffer = nullptr; 33 | while (true) { 34 | //此处加锁是为了防止本线程其他地方同时等待条件变量成立 35 | notify_lock_.lock(); 36 | 37 | //put wait in while cause there can be spurious wake up (due to signal/ENITR) 38 | while (buffer_list_.empty()) { 39 | notify_lock_.wait(); 40 | } 41 | 42 | buffer = buffer_list_.pop_front(); 43 | if(buffer != nullptr) { 44 | msg_head.reset(); 45 | buffer->read_head(msg_head); 46 | int eid = msg_head.eid; 47 | int cid = msg_head.cid; 48 | //传递消息 49 | transmit_msg(msg_head, buffer); 50 | //回收buffer 51 | NODE_MANAGER->push_buffer(eid, cid, buffer); 52 | } 53 | 54 | //操作完成解锁条件变量 55 | notify_lock_.unlock(); 56 | } 57 | return 0; 58 | } 59 | 60 | int Gate_Manager::transmit_msg(Msg_Head &msg_head, Byte_Buffer *buffer) { 61 | GUARD(Session_Map_Lock, mon, session_map_lock_); 62 | if (msg_head.msg_type == TCP_C2S) { 63 | Session_Map::iterator iter = cid_session_map_.find(msg_head.cid); 64 | if (iter == cid_session_map_.end()) { 65 | LOG_ERROR("find_session_by_cid error, eid:%d, cid:%d, msg_type:%d, msg_id:%d, sid:%d", 66 | msg_head.eid, msg_head.cid, msg_head.msg_type, msg_head.msg_id, msg_head.sid); 67 | //client发来的消息,无法找到session,断开连接 68 | V8_MANAGER->push_drop(msg_head.eid, msg_head.cid); 69 | return -1; 70 | } 71 | 72 | msg_head.eid = iter->second->game_eid; 73 | msg_head.cid = iter->second->game_cid; 74 | msg_head.msg_type = NODE_C2S; 75 | msg_head.sid = iter->second->sid; 76 | } else if (msg_head.msg_type == NODE_S2C) { 77 | Session_Map::iterator iter = sid_session_map_.find(msg_head.sid); 78 | if (iter == cid_session_map_.end()) { 79 | LOG_ERROR("find_session_by_sid error, eid:%d, cid:%d, msg_type:%d, msg_id:%d, sid:%d", 80 | msg_head.eid, msg_head.cid, msg_head.msg_type, msg_head.msg_id, msg_head.sid); 81 | return -1; 82 | } 83 | 84 | msg_head.eid = iter->second->client_eid; 85 | msg_head.cid = iter->second->client_cid; 86 | msg_head.msg_type = TCP_S2C; 87 | msg_head.sid = iter->second->sid; 88 | } 89 | NODE_MANAGER->send_msg(msg_head, buffer->get_read_ptr(), buffer->readable_bytes()); 90 | return 0; 91 | } 92 | 93 | int Gate_Manager::add_session(Session *session) { 94 | if (!session) { 95 | LOG_ERROR("node_id:%d, node_name:%s add session error", NODE_MANAGER->node_info().node_id, NODE_MANAGER->node_info().node_name.c_str()); 96 | return -1; 97 | } 98 | 99 | GUARD(Session_Map_Lock, mon, session_map_lock_); 100 | cid_session_map_.insert(std::make_pair(session->client_cid, session)); 101 | sid_session_map_.insert(std::make_pair(session->sid, session)); 102 | return 0; 103 | } 104 | 105 | int Gate_Manager::remove_session(int cid) { 106 | GUARD(Session_Map_Lock, mon, session_map_lock_); 107 | Session_Map::iterator iter = cid_session_map_.find(cid); 108 | if (iter != sid_session_map_.end()) { 109 | Session *session = iter->second; 110 | cid_session_map_.erase(iter); 111 | sid_session_map_.erase(session->sid); 112 | session_pool_.push(session); 113 | } 114 | return 0; 115 | } -------------------------------------------------------------------------------- /plugin/gate/Gate_Manager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Gate_Manager.h 3 | * 4 | * Created on: Nov 8, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef GATE_MANAGER_H_ 9 | #define GATE_MANAGER_H_ 10 | 11 | #include 12 | #include "Buffer_List.h" 13 | #include "Object_Pool.h" 14 | #include "Thread.h" 15 | 16 | struct Session { 17 | int client_eid; //gate向client发消息的端点id 18 | int client_cid; //client与gate连接的cid 19 | int game_eid; //gate向game发消息的端点id 20 | int game_cid; //game与gate连接的cid 21 | uint sid; //gate生成的全局唯一session_id 22 | }; 23 | 24 | class Gate_Manager: public Thread { 25 | typedef Object_Pool Session_Pool; 26 | typedef Mutex_Lock Session_Map_Lock; 27 | typedef std::unordered_map Session_Map; 28 | typedef Buffer_List Data_List; 29 | public: 30 | static Gate_Manager *instance(void); 31 | 32 | virtual void run_handler(void); 33 | virtual int process_list(void); 34 | 35 | inline Session *pop_session(void) { return session_pool_.pop(); } 36 | int add_session(Session *session); 37 | int remove_session(int cid); 38 | 39 | inline void push_buffer(Byte_Buffer *buffer) { 40 | notify_lock_.lock(); 41 | buffer_list_.push_back(buffer); 42 | notify_lock_.signal(); 43 | notify_lock_.unlock(); 44 | } 45 | //传递消息 46 | int transmit_msg(Msg_Head &msg_head, Byte_Buffer *buffer); 47 | 48 | private: 49 | Gate_Manager(void); 50 | virtual ~Gate_Manager(void); 51 | Gate_Manager(const Gate_Manager &); 52 | const Gate_Manager &operator=(const Gate_Manager &); 53 | 54 | private: 55 | static Gate_Manager *instance_; 56 | 57 | Session_Pool session_pool_; 58 | Session_Map_Lock session_map_lock_; 59 | Session_Map cid_session_map_; //cid--session_info 60 | Session_Map sid_session_map_; //sid--session_info 61 | 62 | Data_List buffer_list_; //消息列表 63 | }; 64 | 65 | #define GATE_MANAGER Gate_Manager::instance() 66 | 67 | #endif /* GATE_MANAGER_H_ */ 68 | -------------------------------------------------------------------------------- /plugin/gate/Gate_Wrap.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Gate_Wrap.cpp 3 | * 4 | * Created on: Nov 8, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "Gate_Manager.h" 9 | #include "Gate_Wrap.h" 10 | 11 | void add_session(const FunctionCallbackInfo& args) { 12 | if (args.Length() != 1 || !args[0]->IsObject()) { 13 | LOG_ERROR("add_session args error, length: %d\n", args.Length()); 14 | return; 15 | } 16 | 17 | Session *session = GATE_MANAGER->pop_session(); 18 | if (!session) { 19 | LOG_ERROR("pop session error"); 20 | return; 21 | } 22 | 23 | HandleScope handle_scope(args.GetIsolate()); 24 | Local context(args.GetIsolate()->GetCurrentContext()); 25 | Local object = args[0]->ToObject(context).ToLocalChecked(); 26 | session->client_eid = (object->Get(context, 27 | String::NewFromUtf8(args.GetIsolate(), "client_eid", NewStringType::kNormal). 28 | ToLocalChecked()).ToLocalChecked())->Int32Value(context).FromJust(); 29 | session->client_cid = (object->Get(context, 30 | String::NewFromUtf8(args.GetIsolate(), "client_cid", NewStringType::kNormal). 31 | ToLocalChecked()).ToLocalChecked())->Int32Value(context).FromJust(); 32 | session->game_eid = (object->Get(context, 33 | String::NewFromUtf8(args.GetIsolate(), "game_eid", NewStringType::kNormal). 34 | ToLocalChecked()).ToLocalChecked())->Int32Value(context).FromJust(); 35 | session->game_cid = (object->Get(context, 36 | String::NewFromUtf8(args.GetIsolate(), "game_cid", NewStringType::kNormal). 37 | ToLocalChecked()).ToLocalChecked())->Int32Value(context).FromJust(); 38 | session->sid = (object->Get(context, 39 | String::NewFromUtf8(args.GetIsolate(), "sid", NewStringType::kNormal). 40 | ToLocalChecked()).ToLocalChecked())->Uint32Value(context).FromJust(); 41 | 42 | GATE_MANAGER->add_session(session); 43 | } 44 | 45 | void remove_session(const FunctionCallbackInfo& args) { 46 | if (args.Length() != 1) { 47 | LOG_ERROR("remove_session args error, length: %d\n", args.Length()); 48 | return; 49 | } 50 | 51 | HandleScope handle_scope(args.GetIsolate()); 52 | Local context(args.GetIsolate()->GetCurrentContext()); 53 | int cid = args[0]->Int32Value(context).FromMaybe(0); 54 | GATE_MANAGER->remove_session(cid); 55 | } 56 | -------------------------------------------------------------------------------- /plugin/gate/Gate_Wrap.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Gate_Wrap.h 3 | * 4 | * Created on: Nov 8, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef GATE_WRAP_H_ 9 | #define GATE_WRAP_H_ 10 | 11 | #include "include/v8.h" 12 | 13 | using namespace v8; 14 | 15 | //函数说明:增加客户端连接 参数:1.session信息 返回值:无 16 | void add_session(const FunctionCallbackInfo& args); 17 | //函数说明:移除客户端连接 参数:1.cid 返回值:无 18 | void remove_session(const FunctionCallbackInfo& args); 19 | 20 | 21 | #endif /* GATE_WRAP_H_ */ 22 | -------------------------------------------------------------------------------- /plugin/gate/Makefile: -------------------------------------------------------------------------------- 1 | ############################################################################## 2 | # # 3 | # 默认为release模式编译,debug模式请使用参数'MODE=DEBUG' # 4 | # # 5 | ############################################################################## 6 | 7 | ###在这里添加源文件目录### 8 | SRCDIR= ./\ 9 | 10 | ###这里定义目标文件目录### 11 | OBJDIR =../../.obj/gate_obj/ 12 | 13 | TARGET_NAME=gateplugin.so 14 | 15 | BIN=../ 16 | 17 | INCLUDE=-I/usr/local/include/nodelib/base\ 18 | -I/usr/local/include/nodelib/network\ 19 | -I/usr/local/include/nodelib/node\ 20 | -I/usr/local/include/nodelib/v8\ 21 | -I/usr/local/include/nodelib/xml\ 22 | $(addprefix -I, $(SRCDIR)) 23 | 24 | LIBDIR=-L./ 25 | 26 | LIB=-lv8\ 27 | -lv8_libplatform\ 28 | 29 | CC=g++ 30 | 31 | DEPENDS=-MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" 32 | 33 | ifeq ($(MODE), DEBUG) 34 | BUILD_FLAG = -O0 -g3 35 | else 36 | BUILD_FLAG = -O3 37 | endif 38 | 39 | COM_FLAG=-Wall -c -fmessage-length=0 -std=c++11 -fPIC 40 | 41 | LDFLAG=-shared 42 | 43 | BIN_TARGET=$(OBJDIR)bin/$(TARGET_NAME) 44 | 45 | SRCS=$(wildcard $(addsuffix *.cpp, $(SRCDIR))) 46 | 47 | OBJECTS:=$(addprefix $(OBJDIR), $(subst ./,,$(SRCS:.cpp=.o))) 48 | 49 | .PHONY:all mkobjdir clean config 50 | 51 | all:mkobjdir $(BIN_TARGET) 52 | 53 | -include $(OBJECTS:.o=.d) 54 | 55 | $(BIN_TARGET):$(OBJECTS) 56 | @echo "Linking target $@" 57 | $(CC) $(LDFLAG) -o $@ $^ $(LIBDIR) $(LIB) 58 | @echo " " 59 | @echo "Finished building target: $(TARGET_NAME)" 60 | @echo " " 61 | @-cp -f $(BIN_TARGET) $(BIN) 62 | 63 | $(OBJDIR)%.o:%.cpp 64 | ifeq ($(MODE), DEBUG) 65 | @echo "Building DEBUG MODE target $@" 66 | else 67 | @echo "Building RELEASE MODE target $@" 68 | endif 69 | $(CC) $(INCLUDE) $(BUILD_FLAG) $(COM_FLAG) $(DEPENDS) -o "$(@)" "$(<)" 70 | @echo " " 71 | 72 | mkobjdir: 73 | @test -d $(OBJDIR) || (mkdir $(OBJDIR) && mkdir $(OBJDIR)bin $(addprefix $(OBJDIR), $(subst ./,,$(SRCDIR)))) 74 | 75 | clean: 76 | -rm -rf $(OBJDIR) 77 | -------------------------------------------------------------------------------- /plugin/gate/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * main.cpp 3 | * 4 | * Created on: Nov 8, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "Node_Define.h" 9 | #include "Gate_Wrap.h" 10 | #include "Gate_Manager.h" 11 | 12 | using namespace v8; 13 | 14 | extern "C" { 15 | void init(Local &global, Isolate *isolate) { 16 | global->Set(String::NewFromUtf8(isolate, "add_session", NewStringType::kNormal).ToLocalChecked(), 17 | FunctionTemplate::New(isolate, add_session)); 18 | global->Set(String::NewFromUtf8(isolate, "remove_session", NewStringType::kNormal).ToLocalChecked(), 19 | FunctionTemplate::New(isolate, remove_session)); 20 | } 21 | 22 | void create_thread(const Node_Info &node_info) { 23 | GATE_MANAGER->thr_create(); 24 | } 25 | 26 | void push_buffer(Byte_Buffer *buffer) { 27 | GATE_MANAGER->push_buffer(buffer); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /plugin/log/Log_Manager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Log_Manager.h 3 | * 4 | * Created on: Nov 9, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #ifndef LOG_MANAGER_H_ 9 | #define LOG_MANAGER_H_ 10 | 11 | #include 12 | #include 13 | #include "Bit_Buffer.h" 14 | #include "Buffer_List.h" 15 | #include "Object_Pool.h" 16 | #include "Thread.h" 17 | #include "Node_Define.h" 18 | 19 | enum Msg_Id { 20 | SYNC_NODE_INFO = 1, 21 | SYNC_SAVE_DB_DATA = 250, 22 | }; 23 | 24 | class Log_Manager: public Thread { 25 | typedef Buffer_List Data_List; 26 | typedef std::unordered_set Int_Set; 27 | typedef std::vector Int_Vec; 28 | public: 29 | static Log_Manager *instance(void); 30 | 31 | int init(const Node_Info &node_info); 32 | virtual void run_handler(void); 33 | virtual int process_list(void); 34 | 35 | inline void push_buffer(Byte_Buffer *buffer) { 36 | notify_lock_.lock(); 37 | buffer_list_.push_back(buffer); 38 | notify_lock_.signal(); 39 | notify_lock_.unlock(); 40 | } 41 | 42 | int save_db_data(Bit_Buffer &buffer); 43 | 44 | private: 45 | Log_Manager(void); 46 | virtual ~Log_Manager(void); 47 | Log_Manager(const Log_Manager &); 48 | const Log_Manager &operator=(const Log_Manager &); 49 | 50 | private: 51 | static Log_Manager *instance_; 52 | 53 | Data_List buffer_list_; //消息列表 54 | Node_Info node_info_; //节点信息 55 | int log_node_idx_; //log链接器id索引 56 | int log_connector_size_; //log链接器数量 57 | Int_Vec log_connector_list_;//log链接器cid列表 58 | Int_Set log_fork_list_; //log进程启动列表 59 | }; 60 | 61 | #define LOG_MANAGER Log_Manager::instance() 62 | 63 | #endif /* LOG_MANAGER_H_ */ 64 | -------------------------------------------------------------------------------- /plugin/log/Makefile: -------------------------------------------------------------------------------- 1 | ############################################################################## 2 | # # 3 | # 默认为release模式编译,debug模式请使用参数'MODE=DEBUG' # 4 | # # 5 | ############################################################################## 6 | 7 | ###在这里添加源文件目录### 8 | SRCDIR= ./\ 9 | 10 | ###这里定义目标文件目录### 11 | OBJDIR =../../.obj/log_obj/ 12 | 13 | TARGET_NAME=logplugin.so 14 | 15 | BIN=../ 16 | 17 | INCLUDE=-I/usr/local/include/nodelib/base\ 18 | -I/usr/local/include/nodelib/db\ 19 | -I/usr/local/include/nodelib/network\ 20 | -I/usr/local/include/nodelib/node\ 21 | -I/usr/local/include/nodelib/struct\ 22 | -I/usr/local/include/nodelib/v8\ 23 | -I/usr/local/include/nodelib/xml\ 24 | $(addprefix -I, $(SRCDIR)) 25 | 26 | LIBDIR=-L./ 27 | 28 | LIB=-lv8\ 29 | -lv8_libplatform\ 30 | -lmysqlcppconn\ 31 | 32 | CC=g++ 33 | 34 | DEPENDS=-MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" 35 | 36 | ifeq ($(MODE), DEBUG) 37 | BUILD_FLAG = -O0 -g3 38 | else 39 | BUILD_FLAG = -O3 40 | endif 41 | 42 | COM_FLAG=-Wall -c -fmessage-length=0 -std=c++11 -fPIC 43 | 44 | LDFLAG=-shared 45 | 46 | BIN_TARGET=$(OBJDIR)bin/$(TARGET_NAME) 47 | 48 | SRCS=$(wildcard $(addsuffix *.cpp, $(SRCDIR))) 49 | 50 | OBJECTS:=$(addprefix $(OBJDIR), $(subst ./,,$(SRCS:.cpp=.o))) 51 | 52 | .PHONY:all mkobjdir clean config 53 | 54 | all:mkobjdir $(BIN_TARGET) 55 | 56 | -include $(OBJECTS:.o=.d) 57 | 58 | $(BIN_TARGET):$(OBJECTS) 59 | @echo "Linking target $@" 60 | $(CC) $(LDFLAG) -o $@ $^ $(LIBDIR) $(LIB) 61 | @echo " " 62 | @echo "Finished building target: $(TARGET_NAME)" 63 | @echo " " 64 | @-cp -f $(BIN_TARGET) $(BIN) 65 | 66 | $(OBJDIR)%.o:%.cpp 67 | ifeq ($(MODE), DEBUG) 68 | @echo "Building DEBUG MODE target $@" 69 | else 70 | @echo "Building RELEASE MODE target $@" 71 | endif 72 | $(CC) $(INCLUDE) $(BUILD_FLAG) $(COM_FLAG) $(DEPENDS) -o "$(@)" "$(<)" 73 | @echo " " 74 | 75 | mkobjdir: 76 | @test -d $(OBJDIR) || (mkdir $(OBJDIR) && mkdir $(OBJDIR)bin $(addprefix $(OBJDIR), $(subst ./,,$(SRCDIR)))) 77 | 78 | clean: 79 | -rm -rf $(OBJDIR) 80 | -------------------------------------------------------------------------------- /plugin/log/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * main.cpp 3 | * 4 | * Created on: Nov 9, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "include/v8.h" 9 | #include "Data_Manager.h" 10 | #include "Log_Manager.h" 11 | 12 | using namespace v8; 13 | 14 | extern "C" { 15 | void init(Local &global, Isolate *isolate) {} 16 | 17 | void create_thread(const Node_Info &node_info) { 18 | DATA_MANAGER->init_db_operator(); 19 | LOG_MANAGER->init(node_info); 20 | LOG_MANAGER->thr_create(); 21 | } 22 | 23 | void push_buffer(Byte_Buffer *buffer) { 24 | LOG_MANAGER->push_buffer(buffer); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /plugin/monitor/Makefile: -------------------------------------------------------------------------------- 1 | ############################################################################## 2 | # # 3 | # 默认为release模式编译,debug模式请使用参数'MODE=DEBUG' # 4 | # # 5 | ############################################################################## 6 | 7 | ###在这里添加源文件目录### 8 | SRCDIR= ./\ 9 | 10 | ###这里定义目标文件目录### 11 | OBJDIR =../../.obj/monitor_obj/ 12 | 13 | TARGET_NAME=monitorplugin.so 14 | 15 | BIN=../ 16 | 17 | INCLUDE=-I/usr/local/include/nodelib/base\ 18 | -I/usr/local/include/nodelib/network\ 19 | -I/usr/local/include/nodelib/node\ 20 | -I/usr/local/include/nodelib/v8\ 21 | -I/usr/local/include/nodelib/xml\ 22 | $(addprefix -I, $(SRCDIR)) 23 | 24 | LIBDIR=-L./ 25 | 26 | LIB=-lv8\ 27 | -lv8_libplatform\ 28 | 29 | CC=g++ 30 | 31 | DEPENDS=-MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" 32 | 33 | ifeq ($(MODE), DEBUG) 34 | BUILD_FLAG = -O0 -g3 35 | else 36 | BUILD_FLAG = -O3 37 | endif 38 | 39 | COM_FLAG=-Wall -c -fmessage-length=0 -std=c++11 -fPIC 40 | 41 | LDFLAG=-shared 42 | 43 | BIN_TARGET=$(OBJDIR)bin/$(TARGET_NAME) 44 | 45 | SRCS=$(wildcard $(addsuffix *.cpp, $(SRCDIR))) 46 | 47 | OBJECTS:=$(addprefix $(OBJDIR), $(subst ./,,$(SRCS:.cpp=.o))) 48 | 49 | .PHONY:all mkobjdir clean config 50 | 51 | all:mkobjdir $(BIN_TARGET) 52 | 53 | -include $(OBJECTS:.o=.d) 54 | 55 | $(BIN_TARGET):$(OBJECTS) 56 | @echo "Linking target $@" 57 | $(CC) $(LDFLAG) -o $@ $^ $(LIBDIR) $(LIB) 58 | @echo " " 59 | @echo "Finished building target: $(TARGET_NAME)" 60 | @echo " " 61 | @-cp -f $(BIN_TARGET) $(BIN) 62 | 63 | $(OBJDIR)%.o:%.cpp 64 | ifeq ($(MODE), DEBUG) 65 | @echo "Building DEBUG MODE target $@" 66 | else 67 | @echo "Building RELEASE MODE target $@" 68 | endif 69 | $(CC) $(INCLUDE) $(BUILD_FLAG) $(COM_FLAG) $(DEPENDS) -o "$(@)" "$(<)" 70 | @echo " " 71 | 72 | mkobjdir: 73 | @test -d $(OBJDIR) || (mkdir $(OBJDIR) && mkdir $(OBJDIR)bin $(addprefix $(OBJDIR), $(subst ./,,$(SRCDIR)))) 74 | 75 | clean: 76 | -rm -rf $(OBJDIR) 77 | -------------------------------------------------------------------------------- /plugin/monitor/Monitor_Manager.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Monitor_Manager.cpp 3 | * 4 | * Created on: Dec 26, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "Base_Function.h" 9 | #include "Bit_Buffer.h" 10 | #include "Node_Manager.h" 11 | #include "Monitor_Manager.h" 12 | 13 | Monitor_Manager::Monitor_Manager(void) { } 14 | 15 | Monitor_Manager::~Monitor_Manager(void) { } 16 | 17 | Monitor_Manager *Monitor_Manager::instance_; 18 | 19 | Monitor_Manager *Monitor_Manager::instance(void) { 20 | if (instance_ == 0) 21 | instance_ = new Monitor_Manager; 22 | return instance_; 23 | } 24 | 25 | void Monitor_Manager::run_handler(void) { 26 | process_list(); 27 | } 28 | 29 | int Monitor_Manager::process_list(void) { 30 | std::ostringstream fifo_stream; 31 | fifo_stream << NODE_FIFO << "_" << node_info_.node_id; 32 | 33 | while(true) { 34 | //循环从fifo读数据,读到数据就创建新进程 35 | Byte_Buffer buffer; 36 | buffer.ensure_writable_bytes(1024); 37 | int real_read = read_fifo(fifo_stream.str().c_str(), buffer.get_write_ptr(), buffer.writable_bytes()); 38 | if (real_read > 0) { 39 | //读取数据完毕,设置写指针,否则从buf里面读取数据将会报错 40 | buffer.set_write_idx(buffer.get_write_idx() + real_read); 41 | int eid = 0; 42 | int cid = 0; 43 | int sid = 0; 44 | buffer.read_int32(eid); 45 | buffer.read_int32(cid); 46 | buffer.read_int32(sid); 47 | LOG_INFO("read from fifo:%s,real_read:%d,eid:%d,cid:%d,sid:%d", fifo_stream.str().c_str(), real_read, eid, cid, sid); 48 | sync_node_stack_info(eid, cid, sid); 49 | } 50 | 51 | //短暂睡眠,开启下次循环 52 | Time_Value::sleep(Time_Value(0, 500*1000)); 53 | } 54 | return 0; 55 | } 56 | 57 | int Monitor_Manager::sync_node_stack_info(int eid, int cid, int sid) { 58 | int drop_cid = V8_MANAGER->drop_cid(); 59 | int timer_id = V8_MANAGER->timer_id(); 60 | Msg_Head stack_msg_head = V8_MANAGER->msg_head(); 61 | std::string stack_trace = ""; 62 | 63 | Bit_Buffer bit_buffer; 64 | bit_buffer.write_int(drop_cid, 32); 65 | bit_buffer.write_int(timer_id, 32); 66 | bit_buffer.write_int(stack_msg_head.msg_id, 32); 67 | bit_buffer.write_int(stack_msg_head.msg_type, 32); 68 | bit_buffer.write_int(stack_msg_head.sid, 32); 69 | bit_buffer.write_str(stack_trace.c_str()); 70 | Msg_Head msg_head; 71 | msg_head.eid = eid; 72 | msg_head.cid = cid; 73 | msg_head.protocol = TCP; 74 | msg_head.msg_id = SYNC_NODE_STACK_INFO; 75 | msg_head.msg_type = NODE_MSG; 76 | msg_head.sid = sid; 77 | NODE_MANAGER->send_msg(msg_head, bit_buffer.data(), bit_buffer.get_byte_size()); 78 | return 0; 79 | } -------------------------------------------------------------------------------- /plugin/monitor/Monitor_Manager.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javapretty/node_server/52584b8397fd0f08f562f7e19ca1f073598e6463/plugin/monitor/Monitor_Manager.h -------------------------------------------------------------------------------- /plugin/monitor/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * main.cpp 3 | * 4 | * Created on: Nov 8, 2016 5 | * Author: zhangyalei 6 | */ 7 | 8 | #include "include/v8.h" 9 | #include "Node_Define.h" 10 | #include "Monitor_Manager.h" 11 | 12 | using namespace v8; 13 | 14 | extern "C" { 15 | void init(Local &global, Isolate *isolate) {} 16 | 17 | void create_thread(const Node_Info &node_info) { 18 | MONITOR_MANAGER->init(node_info); 19 | MONITOR_MANAGER->thr_create(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | chmod 777 ./daemon_server ./node_server 4 | 5 | ./daemon_server & 6 | #pid=(`ps aux | grep 'daemon_server' | grep -v 'grep' | awk '{print $2}'`) 7 | #echo daemon_server started, pid[$pid] 8 | echo daemon_server started. 9 | --------------------------------------------------------------------------------