├── README.md ├── common ├── include │ ├── NetDefine.h │ ├── epoller.h │ ├── list.h │ ├── log.h │ ├── message_process.h │ ├── netserver.pb.h │ ├── singleton.h │ ├── socket_connect.h │ └── socket_listen.h ├── makefile ├── netserver.proto └── src │ ├── epoller.cpp │ ├── log.cpp │ ├── message_process.cpp │ ├── netserver.pb.cc │ ├── socket_connect.cpp │ └── socket_listen.cpp ├── makefile ├── net_client.cpp └── net_server.cpp /README.md: -------------------------------------------------------------------------------- 1 | # common_protocol 2 | 简介:最简单的tcpserver,主要解决tcp的粘包、分包的问题,定义了一个通用的包结构,包头+包体,包体是pb协议 3 | 本代码编译和安装时都使用了pb库,运行时需要pb的so库,所以需要首先指明路径: 4 | export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/protobuf2.4.1/lib 5 | 然后在运行才可以 6 | 7 | -------------------------------------------------------------------------------- /common/include/NetDefine.h: -------------------------------------------------------------------------------- 1 | #ifndef NET_DEFINE_H 2 | #define NET_DEFINE_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include "log.h" 8 | 9 | using namespace CGI_LOG; 10 | 11 | #define MaxPacketLength 65536 12 | 13 | /* 命令字 */ 14 | typedef enum 15 | { 16 | CMD_NULL = 0, 17 | CMD_GetUserName = 1, 18 | CMD_SetUserName = 2 19 | } PacketCmd; 20 | 21 | typedef enum 22 | { 23 | RetServerSucc = 0, // 0 - [正常数据, 处理成功] 24 | RetServerFailed = 1, // 1 - [正常数据, 处理失败] 25 | QzoneServerBusy = 2, // 2 - [正常数据, 服务器忙, 可重试] 26 | }RetServerResponse; 27 | 28 | /* 29 | * protocol head 30 | ----------------------------------------------------------------------------------------------------------- 31 | | 版本(4 bytes) | 命令字(4 bytes) | 序列号(4 bytes) | server回应标识(4 byte) | 协议总长度(4 bytes) | 协议体 | 32 | ----------------------------------------------------------------------------------------------------------- 33 | */ 34 | #pragma pack(push,1) 35 | typedef struct stPacketHead 36 | { 37 | uint32_t version; // 版本 38 | uint32_t cmd; // 命令字 39 | uint32_t serialNo; // 序列号 40 | uint32_t result; // 回包专用字段 41 | uint32_t uiPacketLen; // 包体长度 42 | 43 | stPacketHead() 44 | { 45 | version = 0; 46 | cmd = CMD_NULL; 47 | serialNo = 0; 48 | result = 0; 49 | uiPacketLen = 0; 50 | } 51 | 52 | void Encode() 53 | { 54 | version = htonl(version); 55 | cmd = htonl(cmd); 56 | serialNo = htonl(serialNo); 57 | result = htonl(result); 58 | uiPacketLen = htonl(uiPacketLen); 59 | } 60 | 61 | void Decode() 62 | { 63 | version = ntohl(version); 64 | cmd = ntohl(cmd); 65 | serialNo = ntohl(serialNo); 66 | result = ntohl(result); 67 | uiPacketLen = ntohl(uiPacketLen); 68 | } 69 | 70 | }PacketHead; 71 | 72 | /* 封包对象[包头&包体] */ 73 | typedef struct 74 | { 75 | PacketHead netPacketHead;//包头 76 | char * packetBody;//包体 77 | void Encode() 78 | { 79 | netPacketHead.Encode(); 80 | } 81 | } NetPacket; 82 | #pragma pack(pop) 83 | 84 | const uint32_t PacketHeadLength = sizeof(PacketHead); 85 | 86 | #define transferBufferToPacketHead(buffer, header)\ 87 | {\ 88 | memcpy(&(header.version), buffer, sizeof(uint32_t));\ 89 | memcpy(&(header.cmd), buffer+sizeof(uint32_t), sizeof(uint32_t));\ 90 | memcpy(&(header.serialNo), buffer+2*sizeof(uint32_t), sizeof(uint32_t));\ 91 | memcpy(&(header.result), buffer+3*sizeof(uint32_t), sizeof(uint32_t));\ 92 | memcpy(&(header.uiPacketLen), buffer+4*sizeof(uint32_t), sizeof(uint32_t));\ 93 | header.Encode();\ 94 | API_LOG_DEBUG(LM_TRACE,"version:%d, cmd:%d, serialNo:%d, uiPacketLen:%d, result:%d\n",header.version, header.cmd, header.serialNo, header.uiPacketLen,header.result);\ 95 | } 96 | 97 | #endif 98 | -------------------------------------------------------------------------------- /common/include/epoller.h: -------------------------------------------------------------------------------- 1 | #ifndef _EPOLLER_H_ 2 | #define _EPOLLER_H_ 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include "list.h" 18 | #include "log.h" 19 | 20 | using namespace std; 21 | using namespace CGI_LOG; 22 | 23 | #ifndef NET_ERRMSG_SIZE 24 | #define NET_ERRMSG_SIZE 512 25 | #endif 26 | 27 | class CEPoller; 28 | class CEpollSocket; 29 | struct OBJECTMAP 30 | { 31 | int id; 32 | void* objaddr; 33 | struct list_head list_item; 34 | }; 35 | 36 | class CObjectMap 37 | { 38 | public: 39 | CObjectMap(); 40 | ~CObjectMap(); 41 | 42 | int CreateMap(int map_size); 43 | int AddMapObj(int id,void* obj); 44 | int DelMapObj(int id); 45 | void* GetMapObj(int id); 46 | int DropMap(); 47 | static CObjectMap* Instance(); 48 | private: 49 | static CObjectMap* _ins; 50 | struct OBJECTMAP* hash_table; 51 | int hash_table_size; 52 | }; 53 | 54 | 55 | #define EPOLL_FD_MAX 10240 56 | class CEPoller 57 | { 58 | public: 59 | CEPoller(); 60 | ~CEPoller(); 61 | 62 | int Create(int maxfd); 63 | int AddEpollIO(int fd,unsigned flag); 64 | int ModEpollIO(int fd,unsigned flag); 65 | int SetEpollIO(int fd,unsigned flag); 66 | int DelEpollIO(int fd); 67 | void AttachSocket(CEpollSocket* sock); 68 | void DetachSocket(CEpollSocket* sock); 69 | int LoopForEvent(int timeout); 70 | char * GetErrMsg(); 71 | protected: 72 | char _err_msg[NET_ERRMSG_SIZE]; 73 | int _epoll_fd; //epoll的句柄 74 | epoll_event _events[EPOLL_FD_MAX]; //epoll_wait的返回的事件 75 | int _maxfd; 76 | 77 | CObjectMap _obj_map; 78 | }; 79 | 80 | #define FD_RECV EPOLLIN 81 | #define FD_SEND EPOLLOUT 82 | #define FD_CLOSE EPOLLHUP 83 | #define FD_ERROR EPOLLERR 84 | class CEpollSocket 85 | { 86 | public: 87 | CEpollSocket(); 88 | virtual ~CEpollSocket(); 89 | 90 | virtual int OnRecv(){return 0;}; 91 | virtual int OnSend(){return 0;}; 92 | virtual int OnClose(){return 0;}; 93 | virtual int OnError(){return 0;}; 94 | 95 | int GetSockHandle(); 96 | int SetSockHandle(int fd); 97 | int AttachEpoller(CEPoller* epoller); 98 | int DetachEpoller(); 99 | 100 | int SetEvent(unsigned event); 101 | int DropSocket(); 102 | CEPoller* _epoller; //关联的epoller 103 | int _sock_fd; //数据处理的句柄 104 | protected: 105 | bool _event_flag; 106 | int m_iLSID; 107 | int m_mod_ret; 108 | 109 | }; 110 | 111 | 112 | #endif 113 | -------------------------------------------------------------------------------- /common/include/list.h: -------------------------------------------------------------------------------- 1 | #ifndef _H_LIST_H_ 2 | #define _H_LIST_H_ 3 | #include 4 | #include 5 | 6 | __BEGIN_DECLS 7 | /* 8 | * Simple doubly linked list implementation. 9 | * 10 | * Some of the internal functions ("__xxx") are useful when 11 | * manipulating whole lists rather than single entries, as 12 | * sometimes we already know the next/prev entries and we can 13 | * generate better code by using them directly rather than 14 | * using the generic single-entry routines. 15 | */ 16 | #define __builtin_prefetch(x,y,z) (void)1 17 | struct list_head { 18 | struct list_head *next, *prev; 19 | }; 20 | typedef struct list_head list_head_t; 21 | 22 | #define LIST_HEAD_INIT(name) { &(name), &(name) } 23 | 24 | #define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name) 25 | 26 | #define INIT_LIST_HEAD(ptr) do { (ptr)->next = (ptr); (ptr)->prev = (ptr); } while (0) 27 | 28 | /* 29 | * Insert a p entry between two known consecutive entries. 30 | * 31 | * This is only for internal list manipulation where we know 32 | * the prev/next entries already! 33 | */ 34 | static inline void __list_add(struct list_head *p, 35 | struct list_head *prev, 36 | struct list_head *next) 37 | { 38 | next->prev = p; 39 | p->next = next; 40 | p->prev = prev; 41 | prev->next = p; 42 | } 43 | 44 | /** 45 | * list_add - add a p entry 46 | * @p: p entry to be added 47 | * @head: list head to add it after 48 | * 49 | * Insert a p entry after the specified head. 50 | * This is good for implementing stacks. 51 | */ 52 | static inline void list_add(struct list_head *p, struct list_head *head) 53 | { 54 | __list_add(p, head, head->next); 55 | } 56 | /** 57 | * list_add_tail - add a p entry 58 | * @p: p entry to be added 59 | * @head: list head to add it before 60 | * 61 | * Insert a p entry before the specified head. 62 | * This is useful for implementing queues. 63 | */ 64 | static inline void list_add_tail(struct list_head *p, struct list_head *head) 65 | { 66 | __list_add(p, head->prev, head); 67 | } 68 | 69 | /* 70 | * Delete a list entry by making the prev/next entries 71 | * point to each other. 72 | * 73 | * This is only for internal list manipulation where we know 74 | * the prev/next entries already! 75 | */ 76 | static inline void __list_del(struct list_head *prev, struct list_head *next) 77 | { 78 | next->prev = prev; 79 | prev->next = next; 80 | } 81 | 82 | /** 83 | * list_del - deletes entry from list. 84 | * @entry: the element to delete from the list. 85 | * Note: list_empty on entry does not return true after this, the entry is in an undefined state. 86 | */ 87 | static inline void list_del(struct list_head *entry) 88 | { 89 | __list_del(entry->prev, entry->next); 90 | entry->next = 0; 91 | entry->prev = 0; 92 | } 93 | 94 | /** 95 | * list_del_init - deletes entry from list and reinitialize it. 96 | * @entry: the element to delete from the list. 97 | */ 98 | static inline void list_del_init(struct list_head *entry) 99 | { 100 | __list_del(entry->prev, entry->next); 101 | INIT_LIST_HEAD(entry); 102 | } 103 | 104 | /** 105 | * list_move - delete from one list and add as another's head 106 | * @list: the entry to move 107 | * @head: the head that will precede our entry 108 | */ 109 | static inline void list_move(struct list_head *list, struct list_head *head) 110 | { 111 | __list_del(list->prev, list->next); 112 | list_add(list, head); 113 | } 114 | /** 115 | * list_move_tail - delete from one list and add as another's tail 116 | * @list: the entry to move 117 | * @head: the head that will follow our entry 118 | */ 119 | static inline void list_move_tail(struct list_head *list, 120 | struct list_head *head) 121 | { 122 | __list_del(list->prev, list->next); 123 | list_add_tail(list, head); 124 | } 125 | 126 | /** 127 | * list_empty - tests whether a list is empty 128 | * @head: the list to test. 129 | */ 130 | static inline int list_empty(const struct list_head *head) 131 | { 132 | return head->next == head; 133 | } 134 | 135 | static inline void __list_splice(struct list_head *list, 136 | struct list_head *head) 137 | { 138 | struct list_head *first = list->next; 139 | struct list_head *last = list->prev; 140 | struct list_head *at = head->next; 141 | 142 | first->prev = head; 143 | head->next = first; 144 | 145 | last->next = at; 146 | at->prev = last; 147 | } 148 | 149 | /** 150 | * list_splice - join two lists 151 | * @list: the p list to add. 152 | * @head: the place to add it in the first list. 153 | */ 154 | static inline void list_splice(struct list_head *list, struct list_head *head) 155 | { 156 | if (!list_empty(list)) 157 | __list_splice(list, head); 158 | } 159 | 160 | /** 161 | * list_splice_init - join two lists and reinitialise the emptied list. 162 | * @list: the p list to add. 163 | * @head: the place to add it in the first list. 164 | * 165 | * The list at @list is reinitialised 166 | */ 167 | static inline void list_splice_init(struct list_head *list, 168 | struct list_head *head) 169 | { 170 | if (!list_empty(list)) { 171 | __list_splice(list, head); 172 | INIT_LIST_HEAD(list); 173 | } 174 | } 175 | 176 | #ifndef offsetof 177 | #if __GNUC__ >= 4 178 | 179 | #define offsetof(type, member) __builtin_offsetof (type, member);printf("this is gcc > 4\n"); 180 | #else 181 | #define offsetof(type, member) (unsigned long)(&((type *)0)->member);printf("this is gcc < 4\n"); 182 | #endif 183 | #endif 184 | 185 | /** 186 | * list_entry - get the struct for this entry 187 | * @ptr: the &struct list_head pointer. 188 | * @type: the type of the struct this is embedded in. 189 | * @member: the name of the list_struct within the struct. 190 | */ 191 | #define list_entry(ptr, type, member) ((type *)((char *)(ptr)-offsetof(type, member))) 192 | 193 | /** 194 | * list_for_each - iterate over a list 195 | * @pos: the &struct list_head to use as a loop counter. 196 | * @head: the head for your list. 197 | */ 198 | #define list_for_each(pos, head) for (pos = (head)->next, __builtin_prefetch(pos->next,0,1); pos != (head); pos = pos->next, __builtin_prefetch(pos->next,0,1)) 199 | 200 | #define __list_for_each(pos, head) for (pos = (head)->next; pos != (head); pos = pos->next) 201 | /** 202 | * list_for_each_prev - iterate over a list backwards 203 | * @pos: the &struct list_head to use as a loop counter. 204 | * @head: the head for your list. 205 | */ 206 | #define list_for_each_prev(pos, head) for (pos = (head)->prev, __builtin_prefetch(pos->prev,0,1); pos != (head); pos = pos->prev, __builtin_prefetch(pos->prev,0,1)) 207 | 208 | #define __list_for_each_prev(pos, head) for (pos = (head)->prev; pos != (head); pos = pos->prev) 209 | 210 | /** 211 | * list_for_each_safe - iterate over a list safe against removal of list entry 212 | * @pos: the &struct list_head to use as a loop counter. 213 | * @n: another &struct list_head to use as temporary storage 214 | * @head: the head for your list. 215 | */ 216 | #define list_for_each_safe(pos, n, head) for (pos = (head)->next, n = pos->next; pos != (head); pos = n, n = pos->next) 217 | 218 | /** 219 | * list_for_each_entry - iterate over list of given type 220 | * @pos: the type * to use as a loop counter. 221 | * @head: the head for your list. 222 | * @member: the name of the list_struct within the struct. 223 | */ 224 | #define list_for_each_entry(pos, head, member) for (pos = list_entry((head)->next, typeof(*pos), member),__builtin_prefetch(pos->member.next,0,1);&pos->member != (head); pos = list_entry(pos->member.next, typeof(*pos), member),__builtin_prefetch(pos->member.next,0,1)) 225 | 226 | __END_DECLS 227 | 228 | 229 | #endif 230 | 231 | -------------------------------------------------------------------------------- /common/include/log.h: -------------------------------------------------------------------------------- 1 | /* 2 | * cgilog.h 3 | * 4 | * Created on: 2014-10-4 5 | * Author: fenngwang 6 | */ 7 | 8 | #ifndef LOG_H_ 9 | #define LOG_H_ 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | namespace CGI_LOG 19 | { 20 | 21 | using namespace std; 22 | 23 | enum CGI_LOG_PRIORITY 24 | { 25 | LM_SHUTDOWN = 01, 26 | LM_TRACE = 02, 27 | LM_DEBUG = 04, 28 | LM_INFO = 010, 29 | LM_NOTICE = 020, 30 | LM_WARNING = 040, 31 | LM_STARTUP = 0100, 32 | LM_ERROR = 0200, 33 | LM_CRITICAL = 0400, 34 | LM_ALERT = 01000, 35 | LM_EMERGENCY = 02000, 36 | LM_MAX = LM_EMERGENCY, 37 | LM_ENSURE_32_BITS = 0x7FFFFFFF 38 | }; 39 | 40 | class CLogFile { 41 | public: 42 | CLogFile() {}; 43 | 44 | int SetLogPath (const string & sLogFilePath) 45 | { 46 | m_sLogFilePath = sLogFilePath + ".log"; 47 | return 0; 48 | }; 49 | 50 | int ShiftFiles(long lMaxLogSize, int iMaxLogNum); 51 | 52 | int WriteLog (const char *sFile, const int iLine, const char *sFunc, int i32Level, const char*pszFormat, va_list ap); 53 | 54 | const char * priority_name(int errCode); 55 | 56 | private: 57 | string m_sLogFilePath; 58 | }; 59 | 60 | 61 | /** 62 | @desc 初始化日志 63 | */ 64 | void CGI_Log_Init(const string & sLogFilePath); 65 | 66 | void CGI_Error_Log_Orig (const char *sFile, const int iLine, const char *sFunc, int i32Level, const char * pszFormat, ...) __attribute((format(printf, 5, 6))); 67 | #define API_LOG_DEBUG(level, args...) CGI_Error_Log_Orig(__FILE__, __LINE__, __FUNCTION__, level, args) 68 | 69 | 70 | } 71 | 72 | #endif /* LOG_H_ */ 73 | -------------------------------------------------------------------------------- /common/include/message_process.h: -------------------------------------------------------------------------------- 1 | /* 2 | * message_process.h 3 | * 4 | * Created on: 2016年2月2日 5 | * Author: fenngwang 6 | */ 7 | 8 | #ifndef COMMON_INCLUDE_MESSAGE_PROCESS_H_ 9 | #define COMMON_INCLUDE_MESSAGE_PROCESS_H_ 10 | 11 | #include 12 | #include "NetDefine.h" 13 | #include "socket_connect.h" 14 | #include 15 | 16 | class Socket_Connect; 17 | 18 | class Message_Process 19 | { 20 | public: 21 | Message_Process(); 22 | ~Message_Process(); 23 | 24 | public: 25 | void setSockConnect(Socket_Connect* sock_connect) { this->sock_connect = sock_connect; }; 26 | 27 | /* 28 | * return < 0: 出错,调用方需要将socket,并从epoll中去掉 29 | * return = 0: 客户端关闭了连接,调用方需要关闭socket,并从epoll中去掉 30 | * return > 0: 成功,收到的数据长度(并不是recv_buffer中的剩余长度哦) 31 | */ 32 | int recv(); 33 | 34 | int send(); 35 | 36 | private: 37 | /* input参数: 38 | -buffer: 数据缓冲区指针 39 | -already_recv_len:已经接收的未处理的数据长度 40 | * output参数: 41 | -already_recv_len:处理后剩余的数据长度,剩余的缓存已经移动到buffer的头部 42 | -ret: < 0 出错 = 0 剩余长度不够一个完整包 > 0 为完整包,全部处理完毕 43 | */ 44 | int process_buffer(char *buffer, uint32_t &already_recv_len); 45 | private: 46 | Socket_Connect * sock_connect; 47 | char recv_buffer[MaxPacketLength]; // 应用层缓接收冲区 48 | uint32_t recv_buffer_index; // 接收缓冲区中未处理的数据长度 49 | uint32_t already_recv_len; // 已经接收到的长度 50 | char send_buffer[MaxPacketLength]; // 应用层发送缓冲区 51 | uint32_t send_buffer_need_len; // 发送缓冲区中需要发送的数据长度 52 | }; 53 | 54 | 55 | 56 | #endif /* COMMON_INCLUDE_MESSAGE_PROCESS_H_ */ 57 | -------------------------------------------------------------------------------- /common/include/netserver.pb.h: -------------------------------------------------------------------------------- 1 | // Generated by the protocol buffer compiler. DO NOT EDIT! 2 | // source: netserver.proto 3 | 4 | #ifndef PROTOBUF_netserver_2eproto__INCLUDED 5 | #define PROTOBUF_netserver_2eproto__INCLUDED 6 | 7 | #include 8 | 9 | #include 10 | 11 | #if GOOGLE_PROTOBUF_VERSION < 2004000 12 | #error This file was generated by a newer version of protoc which is 13 | #error incompatible with your Protocol Buffer headers. Please update 14 | #error your headers. 15 | #endif 16 | #if 2004001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 17 | #error This file was generated by an older version of protoc which is 18 | #error incompatible with your Protocol Buffer headers. Please 19 | #error regenerate this file with a newer version of protoc. 20 | #endif 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | // @@protoc_insertion_point(includes) 27 | 28 | namespace netserver { 29 | 30 | // Internal implementation detail -- do not call these. 31 | void protobuf_AddDesc_netserver_2eproto(); 32 | void protobuf_AssignDesc_netserver_2eproto(); 33 | void protobuf_ShutdownFile_netserver_2eproto(); 34 | 35 | class GetUserNameRequest; 36 | class GetUserNameResponse; 37 | class SetUserNameRequest; 38 | 39 | // =================================================================== 40 | 41 | class GetUserNameRequest : public ::google::protobuf::Message { 42 | public: 43 | GetUserNameRequest(); 44 | virtual ~GetUserNameRequest(); 45 | 46 | GetUserNameRequest(const GetUserNameRequest& from); 47 | 48 | inline GetUserNameRequest& operator=(const GetUserNameRequest& from) { 49 | CopyFrom(from); 50 | return *this; 51 | } 52 | 53 | inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { 54 | return _unknown_fields_; 55 | } 56 | 57 | inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { 58 | return &_unknown_fields_; 59 | } 60 | 61 | static const ::google::protobuf::Descriptor* descriptor(); 62 | static const GetUserNameRequest& default_instance(); 63 | 64 | void Swap(GetUserNameRequest* other); 65 | 66 | // implements Message ---------------------------------------------- 67 | 68 | GetUserNameRequest* New() const; 69 | void CopyFrom(const ::google::protobuf::Message& from); 70 | void MergeFrom(const ::google::protobuf::Message& from); 71 | void CopyFrom(const GetUserNameRequest& from); 72 | void MergeFrom(const GetUserNameRequest& from); 73 | void Clear(); 74 | bool IsInitialized() const; 75 | 76 | int ByteSize() const; 77 | bool MergePartialFromCodedStream( 78 | ::google::protobuf::io::CodedInputStream* input); 79 | void SerializeWithCachedSizes( 80 | ::google::protobuf::io::CodedOutputStream* output) const; 81 | ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; 82 | int GetCachedSize() const { return _cached_size_; } 83 | private: 84 | void SharedCtor(); 85 | void SharedDtor(); 86 | void SetCachedSize(int size) const; 87 | public: 88 | 89 | ::google::protobuf::Metadata GetMetadata() const; 90 | 91 | // nested types ---------------------------------------------------- 92 | 93 | // accessors ------------------------------------------------------- 94 | 95 | // required int32 userId = 1; 96 | inline bool has_userid() const; 97 | inline void clear_userid(); 98 | static const int kUserIdFieldNumber = 1; 99 | inline ::google::protobuf::int32 userid() const; 100 | inline void set_userid(::google::protobuf::int32 value); 101 | 102 | // @@protoc_insertion_point(class_scope:netserver.GetUserNameRequest) 103 | private: 104 | inline void set_has_userid(); 105 | inline void clear_has_userid(); 106 | 107 | ::google::protobuf::UnknownFieldSet _unknown_fields_; 108 | 109 | ::google::protobuf::int32 userid_; 110 | 111 | mutable int _cached_size_; 112 | ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32]; 113 | 114 | friend void protobuf_AddDesc_netserver_2eproto(); 115 | friend void protobuf_AssignDesc_netserver_2eproto(); 116 | friend void protobuf_ShutdownFile_netserver_2eproto(); 117 | 118 | void InitAsDefaultInstance(); 119 | static GetUserNameRequest* default_instance_; 120 | }; 121 | // ------------------------------------------------------------------- 122 | 123 | class GetUserNameResponse : public ::google::protobuf::Message { 124 | public: 125 | GetUserNameResponse(); 126 | virtual ~GetUserNameResponse(); 127 | 128 | GetUserNameResponse(const GetUserNameResponse& from); 129 | 130 | inline GetUserNameResponse& operator=(const GetUserNameResponse& from) { 131 | CopyFrom(from); 132 | return *this; 133 | } 134 | 135 | inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { 136 | return _unknown_fields_; 137 | } 138 | 139 | inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { 140 | return &_unknown_fields_; 141 | } 142 | 143 | static const ::google::protobuf::Descriptor* descriptor(); 144 | static const GetUserNameResponse& default_instance(); 145 | 146 | void Swap(GetUserNameResponse* other); 147 | 148 | // implements Message ---------------------------------------------- 149 | 150 | GetUserNameResponse* New() const; 151 | void CopyFrom(const ::google::protobuf::Message& from); 152 | void MergeFrom(const ::google::protobuf::Message& from); 153 | void CopyFrom(const GetUserNameResponse& from); 154 | void MergeFrom(const GetUserNameResponse& from); 155 | void Clear(); 156 | bool IsInitialized() const; 157 | 158 | int ByteSize() const; 159 | bool MergePartialFromCodedStream( 160 | ::google::protobuf::io::CodedInputStream* input); 161 | void SerializeWithCachedSizes( 162 | ::google::protobuf::io::CodedOutputStream* output) const; 163 | ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; 164 | int GetCachedSize() const { return _cached_size_; } 165 | private: 166 | void SharedCtor(); 167 | void SharedDtor(); 168 | void SetCachedSize(int size) const; 169 | public: 170 | 171 | ::google::protobuf::Metadata GetMetadata() const; 172 | 173 | // nested types ---------------------------------------------------- 174 | 175 | // accessors ------------------------------------------------------- 176 | 177 | // required int32 gender = 1; 178 | inline bool has_gender() const; 179 | inline void clear_gender(); 180 | static const int kGenderFieldNumber = 1; 181 | inline ::google::protobuf::int32 gender() const; 182 | inline void set_gender(::google::protobuf::int32 value); 183 | 184 | // required string name = 2; 185 | inline bool has_name() const; 186 | inline void clear_name(); 187 | static const int kNameFieldNumber = 2; 188 | inline const ::std::string& name() const; 189 | inline void set_name(const ::std::string& value); 190 | inline void set_name(const char* value); 191 | inline void set_name(const char* value, size_t size); 192 | inline ::std::string* mutable_name(); 193 | inline ::std::string* release_name(); 194 | 195 | // optional string province = 3; 196 | inline bool has_province() const; 197 | inline void clear_province(); 198 | static const int kProvinceFieldNumber = 3; 199 | inline const ::std::string& province() const; 200 | inline void set_province(const ::std::string& value); 201 | inline void set_province(const char* value); 202 | inline void set_province(const char* value, size_t size); 203 | inline ::std::string* mutable_province(); 204 | inline ::std::string* release_province(); 205 | 206 | // @@protoc_insertion_point(class_scope:netserver.GetUserNameResponse) 207 | private: 208 | inline void set_has_gender(); 209 | inline void clear_has_gender(); 210 | inline void set_has_name(); 211 | inline void clear_has_name(); 212 | inline void set_has_province(); 213 | inline void clear_has_province(); 214 | 215 | ::google::protobuf::UnknownFieldSet _unknown_fields_; 216 | 217 | ::std::string* name_; 218 | ::std::string* province_; 219 | ::google::protobuf::int32 gender_; 220 | 221 | mutable int _cached_size_; 222 | ::google::protobuf::uint32 _has_bits_[(3 + 31) / 32]; 223 | 224 | friend void protobuf_AddDesc_netserver_2eproto(); 225 | friend void protobuf_AssignDesc_netserver_2eproto(); 226 | friend void protobuf_ShutdownFile_netserver_2eproto(); 227 | 228 | void InitAsDefaultInstance(); 229 | static GetUserNameResponse* default_instance_; 230 | }; 231 | // ------------------------------------------------------------------- 232 | 233 | class SetUserNameRequest : public ::google::protobuf::Message { 234 | public: 235 | SetUserNameRequest(); 236 | virtual ~SetUserNameRequest(); 237 | 238 | SetUserNameRequest(const SetUserNameRequest& from); 239 | 240 | inline SetUserNameRequest& operator=(const SetUserNameRequest& from) { 241 | CopyFrom(from); 242 | return *this; 243 | } 244 | 245 | inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { 246 | return _unknown_fields_; 247 | } 248 | 249 | inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { 250 | return &_unknown_fields_; 251 | } 252 | 253 | static const ::google::protobuf::Descriptor* descriptor(); 254 | static const SetUserNameRequest& default_instance(); 255 | 256 | void Swap(SetUserNameRequest* other); 257 | 258 | // implements Message ---------------------------------------------- 259 | 260 | SetUserNameRequest* New() const; 261 | void CopyFrom(const ::google::protobuf::Message& from); 262 | void MergeFrom(const ::google::protobuf::Message& from); 263 | void CopyFrom(const SetUserNameRequest& from); 264 | void MergeFrom(const SetUserNameRequest& from); 265 | void Clear(); 266 | bool IsInitialized() const; 267 | 268 | int ByteSize() const; 269 | bool MergePartialFromCodedStream( 270 | ::google::protobuf::io::CodedInputStream* input); 271 | void SerializeWithCachedSizes( 272 | ::google::protobuf::io::CodedOutputStream* output) const; 273 | ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; 274 | int GetCachedSize() const { return _cached_size_; } 275 | private: 276 | void SharedCtor(); 277 | void SharedDtor(); 278 | void SetCachedSize(int size) const; 279 | public: 280 | 281 | ::google::protobuf::Metadata GetMetadata() const; 282 | 283 | // nested types ---------------------------------------------------- 284 | 285 | // accessors ------------------------------------------------------- 286 | 287 | // required int32 gender = 1; 288 | inline bool has_gender() const; 289 | inline void clear_gender(); 290 | static const int kGenderFieldNumber = 1; 291 | inline ::google::protobuf::int32 gender() const; 292 | inline void set_gender(::google::protobuf::int32 value); 293 | 294 | // required string name = 2; 295 | inline bool has_name() const; 296 | inline void clear_name(); 297 | static const int kNameFieldNumber = 2; 298 | inline const ::std::string& name() const; 299 | inline void set_name(const ::std::string& value); 300 | inline void set_name(const char* value); 301 | inline void set_name(const char* value, size_t size); 302 | inline ::std::string* mutable_name(); 303 | inline ::std::string* release_name(); 304 | 305 | // optional string province = 3; 306 | inline bool has_province() const; 307 | inline void clear_province(); 308 | static const int kProvinceFieldNumber = 3; 309 | inline const ::std::string& province() const; 310 | inline void set_province(const ::std::string& value); 311 | inline void set_province(const char* value); 312 | inline void set_province(const char* value, size_t size); 313 | inline ::std::string* mutable_province(); 314 | inline ::std::string* release_province(); 315 | 316 | // @@protoc_insertion_point(class_scope:netserver.SetUserNameRequest) 317 | private: 318 | inline void set_has_gender(); 319 | inline void clear_has_gender(); 320 | inline void set_has_name(); 321 | inline void clear_has_name(); 322 | inline void set_has_province(); 323 | inline void clear_has_province(); 324 | 325 | ::google::protobuf::UnknownFieldSet _unknown_fields_; 326 | 327 | ::std::string* name_; 328 | ::std::string* province_; 329 | ::google::protobuf::int32 gender_; 330 | 331 | mutable int _cached_size_; 332 | ::google::protobuf::uint32 _has_bits_[(3 + 31) / 32]; 333 | 334 | friend void protobuf_AddDesc_netserver_2eproto(); 335 | friend void protobuf_AssignDesc_netserver_2eproto(); 336 | friend void protobuf_ShutdownFile_netserver_2eproto(); 337 | 338 | void InitAsDefaultInstance(); 339 | static SetUserNameRequest* default_instance_; 340 | }; 341 | // =================================================================== 342 | 343 | 344 | // =================================================================== 345 | 346 | // GetUserNameRequest 347 | 348 | // required int32 userId = 1; 349 | inline bool GetUserNameRequest::has_userid() const { 350 | return (_has_bits_[0] & 0x00000001u) != 0; 351 | } 352 | inline void GetUserNameRequest::set_has_userid() { 353 | _has_bits_[0] |= 0x00000001u; 354 | } 355 | inline void GetUserNameRequest::clear_has_userid() { 356 | _has_bits_[0] &= ~0x00000001u; 357 | } 358 | inline void GetUserNameRequest::clear_userid() { 359 | userid_ = 0; 360 | clear_has_userid(); 361 | } 362 | inline ::google::protobuf::int32 GetUserNameRequest::userid() const { 363 | return userid_; 364 | } 365 | inline void GetUserNameRequest::set_userid(::google::protobuf::int32 value) { 366 | set_has_userid(); 367 | userid_ = value; 368 | } 369 | 370 | // ------------------------------------------------------------------- 371 | 372 | // GetUserNameResponse 373 | 374 | // required int32 gender = 1; 375 | inline bool GetUserNameResponse::has_gender() const { 376 | return (_has_bits_[0] & 0x00000001u) != 0; 377 | } 378 | inline void GetUserNameResponse::set_has_gender() { 379 | _has_bits_[0] |= 0x00000001u; 380 | } 381 | inline void GetUserNameResponse::clear_has_gender() { 382 | _has_bits_[0] &= ~0x00000001u; 383 | } 384 | inline void GetUserNameResponse::clear_gender() { 385 | gender_ = 0; 386 | clear_has_gender(); 387 | } 388 | inline ::google::protobuf::int32 GetUserNameResponse::gender() const { 389 | return gender_; 390 | } 391 | inline void GetUserNameResponse::set_gender(::google::protobuf::int32 value) { 392 | set_has_gender(); 393 | gender_ = value; 394 | } 395 | 396 | // required string name = 2; 397 | inline bool GetUserNameResponse::has_name() const { 398 | return (_has_bits_[0] & 0x00000002u) != 0; 399 | } 400 | inline void GetUserNameResponse::set_has_name() { 401 | _has_bits_[0] |= 0x00000002u; 402 | } 403 | inline void GetUserNameResponse::clear_has_name() { 404 | _has_bits_[0] &= ~0x00000002u; 405 | } 406 | inline void GetUserNameResponse::clear_name() { 407 | if (name_ != &::google::protobuf::internal::kEmptyString) { 408 | name_->clear(); 409 | } 410 | clear_has_name(); 411 | } 412 | inline const ::std::string& GetUserNameResponse::name() const { 413 | return *name_; 414 | } 415 | inline void GetUserNameResponse::set_name(const ::std::string& value) { 416 | set_has_name(); 417 | if (name_ == &::google::protobuf::internal::kEmptyString) { 418 | name_ = new ::std::string; 419 | } 420 | name_->assign(value); 421 | } 422 | inline void GetUserNameResponse::set_name(const char* value) { 423 | set_has_name(); 424 | if (name_ == &::google::protobuf::internal::kEmptyString) { 425 | name_ = new ::std::string; 426 | } 427 | name_->assign(value); 428 | } 429 | inline void GetUserNameResponse::set_name(const char* value, size_t size) { 430 | set_has_name(); 431 | if (name_ == &::google::protobuf::internal::kEmptyString) { 432 | name_ = new ::std::string; 433 | } 434 | name_->assign(reinterpret_cast(value), size); 435 | } 436 | inline ::std::string* GetUserNameResponse::mutable_name() { 437 | set_has_name(); 438 | if (name_ == &::google::protobuf::internal::kEmptyString) { 439 | name_ = new ::std::string; 440 | } 441 | return name_; 442 | } 443 | inline ::std::string* GetUserNameResponse::release_name() { 444 | clear_has_name(); 445 | if (name_ == &::google::protobuf::internal::kEmptyString) { 446 | return NULL; 447 | } else { 448 | ::std::string* temp = name_; 449 | name_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); 450 | return temp; 451 | } 452 | } 453 | 454 | // optional string province = 3; 455 | inline bool GetUserNameResponse::has_province() const { 456 | return (_has_bits_[0] & 0x00000004u) != 0; 457 | } 458 | inline void GetUserNameResponse::set_has_province() { 459 | _has_bits_[0] |= 0x00000004u; 460 | } 461 | inline void GetUserNameResponse::clear_has_province() { 462 | _has_bits_[0] &= ~0x00000004u; 463 | } 464 | inline void GetUserNameResponse::clear_province() { 465 | if (province_ != &::google::protobuf::internal::kEmptyString) { 466 | province_->clear(); 467 | } 468 | clear_has_province(); 469 | } 470 | inline const ::std::string& GetUserNameResponse::province() const { 471 | return *province_; 472 | } 473 | inline void GetUserNameResponse::set_province(const ::std::string& value) { 474 | set_has_province(); 475 | if (province_ == &::google::protobuf::internal::kEmptyString) { 476 | province_ = new ::std::string; 477 | } 478 | province_->assign(value); 479 | } 480 | inline void GetUserNameResponse::set_province(const char* value) { 481 | set_has_province(); 482 | if (province_ == &::google::protobuf::internal::kEmptyString) { 483 | province_ = new ::std::string; 484 | } 485 | province_->assign(value); 486 | } 487 | inline void GetUserNameResponse::set_province(const char* value, size_t size) { 488 | set_has_province(); 489 | if (province_ == &::google::protobuf::internal::kEmptyString) { 490 | province_ = new ::std::string; 491 | } 492 | province_->assign(reinterpret_cast(value), size); 493 | } 494 | inline ::std::string* GetUserNameResponse::mutable_province() { 495 | set_has_province(); 496 | if (province_ == &::google::protobuf::internal::kEmptyString) { 497 | province_ = new ::std::string; 498 | } 499 | return province_; 500 | } 501 | inline ::std::string* GetUserNameResponse::release_province() { 502 | clear_has_province(); 503 | if (province_ == &::google::protobuf::internal::kEmptyString) { 504 | return NULL; 505 | } else { 506 | ::std::string* temp = province_; 507 | province_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); 508 | return temp; 509 | } 510 | } 511 | 512 | // ------------------------------------------------------------------- 513 | 514 | // SetUserNameRequest 515 | 516 | // required int32 gender = 1; 517 | inline bool SetUserNameRequest::has_gender() const { 518 | return (_has_bits_[0] & 0x00000001u) != 0; 519 | } 520 | inline void SetUserNameRequest::set_has_gender() { 521 | _has_bits_[0] |= 0x00000001u; 522 | } 523 | inline void SetUserNameRequest::clear_has_gender() { 524 | _has_bits_[0] &= ~0x00000001u; 525 | } 526 | inline void SetUserNameRequest::clear_gender() { 527 | gender_ = 0; 528 | clear_has_gender(); 529 | } 530 | inline ::google::protobuf::int32 SetUserNameRequest::gender() const { 531 | return gender_; 532 | } 533 | inline void SetUserNameRequest::set_gender(::google::protobuf::int32 value) { 534 | set_has_gender(); 535 | gender_ = value; 536 | } 537 | 538 | // required string name = 2; 539 | inline bool SetUserNameRequest::has_name() const { 540 | return (_has_bits_[0] & 0x00000002u) != 0; 541 | } 542 | inline void SetUserNameRequest::set_has_name() { 543 | _has_bits_[0] |= 0x00000002u; 544 | } 545 | inline void SetUserNameRequest::clear_has_name() { 546 | _has_bits_[0] &= ~0x00000002u; 547 | } 548 | inline void SetUserNameRequest::clear_name() { 549 | if (name_ != &::google::protobuf::internal::kEmptyString) { 550 | name_->clear(); 551 | } 552 | clear_has_name(); 553 | } 554 | inline const ::std::string& SetUserNameRequest::name() const { 555 | return *name_; 556 | } 557 | inline void SetUserNameRequest::set_name(const ::std::string& value) { 558 | set_has_name(); 559 | if (name_ == &::google::protobuf::internal::kEmptyString) { 560 | name_ = new ::std::string; 561 | } 562 | name_->assign(value); 563 | } 564 | inline void SetUserNameRequest::set_name(const char* value) { 565 | set_has_name(); 566 | if (name_ == &::google::protobuf::internal::kEmptyString) { 567 | name_ = new ::std::string; 568 | } 569 | name_->assign(value); 570 | } 571 | inline void SetUserNameRequest::set_name(const char* value, size_t size) { 572 | set_has_name(); 573 | if (name_ == &::google::protobuf::internal::kEmptyString) { 574 | name_ = new ::std::string; 575 | } 576 | name_->assign(reinterpret_cast(value), size); 577 | } 578 | inline ::std::string* SetUserNameRequest::mutable_name() { 579 | set_has_name(); 580 | if (name_ == &::google::protobuf::internal::kEmptyString) { 581 | name_ = new ::std::string; 582 | } 583 | return name_; 584 | } 585 | inline ::std::string* SetUserNameRequest::release_name() { 586 | clear_has_name(); 587 | if (name_ == &::google::protobuf::internal::kEmptyString) { 588 | return NULL; 589 | } else { 590 | ::std::string* temp = name_; 591 | name_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); 592 | return temp; 593 | } 594 | } 595 | 596 | // optional string province = 3; 597 | inline bool SetUserNameRequest::has_province() const { 598 | return (_has_bits_[0] & 0x00000004u) != 0; 599 | } 600 | inline void SetUserNameRequest::set_has_province() { 601 | _has_bits_[0] |= 0x00000004u; 602 | } 603 | inline void SetUserNameRequest::clear_has_province() { 604 | _has_bits_[0] &= ~0x00000004u; 605 | } 606 | inline void SetUserNameRequest::clear_province() { 607 | if (province_ != &::google::protobuf::internal::kEmptyString) { 608 | province_->clear(); 609 | } 610 | clear_has_province(); 611 | } 612 | inline const ::std::string& SetUserNameRequest::province() const { 613 | return *province_; 614 | } 615 | inline void SetUserNameRequest::set_province(const ::std::string& value) { 616 | set_has_province(); 617 | if (province_ == &::google::protobuf::internal::kEmptyString) { 618 | province_ = new ::std::string; 619 | } 620 | province_->assign(value); 621 | } 622 | inline void SetUserNameRequest::set_province(const char* value) { 623 | set_has_province(); 624 | if (province_ == &::google::protobuf::internal::kEmptyString) { 625 | province_ = new ::std::string; 626 | } 627 | province_->assign(value); 628 | } 629 | inline void SetUserNameRequest::set_province(const char* value, size_t size) { 630 | set_has_province(); 631 | if (province_ == &::google::protobuf::internal::kEmptyString) { 632 | province_ = new ::std::string; 633 | } 634 | province_->assign(reinterpret_cast(value), size); 635 | } 636 | inline ::std::string* SetUserNameRequest::mutable_province() { 637 | set_has_province(); 638 | if (province_ == &::google::protobuf::internal::kEmptyString) { 639 | province_ = new ::std::string; 640 | } 641 | return province_; 642 | } 643 | inline ::std::string* SetUserNameRequest::release_province() { 644 | clear_has_province(); 645 | if (province_ == &::google::protobuf::internal::kEmptyString) { 646 | return NULL; 647 | } else { 648 | ::std::string* temp = province_; 649 | province_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); 650 | return temp; 651 | } 652 | } 653 | 654 | 655 | // @@protoc_insertion_point(namespace_scope) 656 | 657 | } // namespace netserver 658 | 659 | #ifndef SWIG 660 | namespace google { 661 | namespace protobuf { 662 | 663 | 664 | } // namespace google 665 | } // namespace protobuf 666 | #endif // SWIG 667 | 668 | // @@protoc_insertion_point(global_scope) 669 | 670 | #endif // PROTOBUF_netserver_2eproto__INCLUDED 671 | -------------------------------------------------------------------------------- /common/include/singleton.h: -------------------------------------------------------------------------------- 1 | /* 2 | * singleton.h 3 | * 4 | * Created on: 2016-2-1 5 | * Author: wangfeng 6 | */ 7 | 8 | #ifndef SINGLETON_H_ 9 | #define SINGLETON_H_ 10 | 11 | template 12 | class CSingleton { 13 | public: 14 | static T* instance(); 15 | }; 16 | 17 | template 18 | T* CSingleton:: instance() 19 | { 20 | static T _instance; 21 | return &_instance; 22 | } 23 | 24 | #endif /* SINGLETON_H_ */ 25 | -------------------------------------------------------------------------------- /common/include/socket_connect.h: -------------------------------------------------------------------------------- 1 | /* 2 | * socket_connect.h 3 | * 4 | * Created on: 2016-2-2 5 | * Author: wangfeng 6 | */ 7 | 8 | #ifndef SOCKET_CONNECT_H_ 9 | #define SOCKET_CONNECT_H_ 10 | 11 | #include "epoller.h" 12 | #include "socket_listen.h" 13 | #include "message_process.h" 14 | 15 | class Socket_Listen; 16 | class Message_Process; 17 | 18 | class Socket_Connect:public CEpollSocket 19 | { 20 | public: 21 | Socket_Connect(); 22 | ~Socket_Connect(); 23 | 24 | virtual int OnRecv(); 25 | virtual int OnSend(); 26 | virtual int OnClose(); 27 | virtual int OnError(); 28 | 29 | void SetSockListen(Socket_Listen* sock_listen) { _sock_listen = sock_listen; }; 30 | 31 | void setClientIP(const char * strIP){_ip = strIP;} 32 | 33 | string getIP() 34 | { 35 | return _ip; 36 | } 37 | 38 | int getSequence() 39 | { 40 | return seqence; 41 | } 42 | 43 | void setSqeuence(int seq) {seqence = seq;} 44 | 45 | public: 46 | Socket_Listen *_sock_listen; 47 | string _ip; 48 | Message_Process *msg_input; // 数据解析类 49 | int seqence; 50 | }; 51 | 52 | 53 | 54 | 55 | #endif /* SOCKET_CONNECT_H_ */ 56 | -------------------------------------------------------------------------------- /common/include/socket_listen.h: -------------------------------------------------------------------------------- 1 | /* 2 | * socket_listen.h 3 | * 4 | * Created on: 2016-2-2 5 | * Author: wangfeng 6 | */ 7 | 8 | #ifndef SOCKET_LISTEN_H_ 9 | #define SOCKET_LISTEN_H_ 10 | 11 | #include "epoller.h" 12 | #include "log.h" 13 | #include "socket_connect.h" 14 | 15 | using namespace CGI_LOG; 16 | 17 | #ifndef SERVER_PORT 18 | #define SERVER_PORT 9999 19 | #endif 20 | 21 | class Socket_Listen:public CEpollSocket 22 | { 23 | public: 24 | Socket_Listen(); 25 | ~Socket_Listen(); 26 | 27 | int Create(const char* bind_ip,short bind_port); 28 | 29 | virtual int OnRecv(); 30 | virtual int OnSend(); 31 | virtual int OnClose(); 32 | virtual int OnError(); 33 | private: 34 | int AllocConnfd(int connfd); 35 | struct sockaddr_in client_addr; 36 | }; 37 | 38 | 39 | 40 | #endif /* SOCKET_LISTEN_H_ */ 41 | -------------------------------------------------------------------------------- /common/makefile: -------------------------------------------------------------------------------- 1 | ############################################################# 2 | # Makefile for static library. 3 | # 编译静态链接库 4 | ############################################################# 5 | #set your own environment option 6 | 7 | cc = g++ 8 | AR = ar 9 | flags = -W -g -Wno-deprecated -lpthread 10 | INC=-I/usr/local/protobuf2.4.1/include\ 11 | -I/usr/local/sofa-pbrpc/include \ 12 | -I./include 13 | 14 | TARGET=libcommon.a 15 | PROTO_SRC=netserver.proto 16 | 17 | OBJS=$(patsubst src/%.cpp,obj/%.o,$(wildcard src/*.cpp)) 18 | OBJS_PB=$(patsubst %.proto,obj/%.pb.o,$(PROTO_SRC)) 19 | 20 | obj/%.o:src/%.cpp 21 | $(cc) -c $< $(flags) $(INC) -o $@ 22 | obj/%.pb.o:src/%.pb.cc 23 | $(cc) -c $< $(flags) $(INC) -o $@ 24 | %.pb.cc:%.proto 25 | /usr/local/protobuf2.4.1/bin/protoc -I=./ --cpp_out=./ $< 26 | mv *.h include/ 27 | mv *.cc src/ 28 | 29 | $(TARGET):$(OBJS_PB) $(OBJS) 30 | ${AR} -r lib/$@ $(OBJS_PB) $(OBJS) 31 | 32 | clean: 33 | rm -f obj/*.o 34 | rm -f lib/$(TARGET) 35 | -------------------------------------------------------------------------------- /common/netserver.proto: -------------------------------------------------------------------------------- 1 | package netserver; 2 | 3 | //用户信息 4 | message GetUserNameRequest 5 | { 6 | required int32 userId = 1; 7 | } 8 | 9 | message GetUserNameResponse 10 | { 11 | required int32 gender = 1; // 性别 12 | required string name = 2; // 名字 13 | optional string province = 3; // 省份 14 | } 15 | 16 | message SetUserNameRequest 17 | { 18 | required int32 gender = 1; 19 | required string name = 2; 20 | optional string province = 3; 21 | } -------------------------------------------------------------------------------- /common/src/epoller.cpp: -------------------------------------------------------------------------------- 1 | #include "epoller.h" 2 | //#include "idle_conn_pool.h" 3 | //extern CIdleConnPool g_idle_conn_pool; 4 | 5 | CObjectMap* CObjectMap::_ins = NULL; 6 | CObjectMap* CObjectMap::Instance() 7 | { 8 | if ( !_ins ) 9 | _ins = new CObjectMap(); 10 | return _ins; 11 | } 12 | 13 | CObjectMap::CObjectMap() 14 | { 15 | hash_table_size = 0; 16 | hash_table = NULL; 17 | } 18 | 19 | CObjectMap::~CObjectMap() 20 | { 21 | if ( hash_table ) 22 | { 23 | DropMap(); 24 | } 25 | } 26 | 27 | int CObjectMap::CreateMap(int map_size) 28 | { 29 | hash_table = new struct OBJECTMAP[map_size]; 30 | if ( !hash_table ) return -1; 31 | 32 | for(int i=0;iid = id; 53 | item->objaddr = obj; 54 | list_add_tail(&item->list_item,&hash_table[idx].list_item); 55 | 56 | return 0; 57 | } 58 | 59 | int CObjectMap::DelMapObj(int id) 60 | { 61 | int idx = id%hash_table_size; 62 | 63 | struct list_head* _head; 64 | struct list_head* _tmp1; 65 | struct list_head* _tmp2; 66 | struct OBJECTMAP* item; 67 | 68 | _head = &hash_table[idx].list_item; 69 | list_for_each_safe(_tmp1,_tmp2,_head) 70 | { 71 | item = list_entry(_tmp1,struct OBJECTMAP,list_item); 72 | if ( item->id == id ) 73 | { 74 | list_del(_tmp1); 75 | delete item; 76 | return 0; 77 | } 78 | } 79 | 80 | return -1; 81 | } 82 | 83 | void* CObjectMap::GetMapObj(int id) 84 | { 85 | int idx = id%hash_table_size; 86 | 87 | struct list_head* _head; 88 | struct list_head* _tmp; 89 | struct OBJECTMAP* item; 90 | 91 | _head = &hash_table[idx].list_item; 92 | list_for_each(_tmp,_head) 93 | { 94 | item = list_entry(_tmp,struct OBJECTMAP,list_item); 95 | if ( item->id == id ) 96 | { 97 | return item->objaddr; 98 | } 99 | } 100 | 101 | return NULL; 102 | } 103 | 104 | int CObjectMap::DropMap() 105 | { 106 | struct list_head* _head; 107 | struct list_head* _tmp1; 108 | struct list_head* _tmp2; 109 | struct OBJECTMAP* item; 110 | 111 | for( int i=0;iGetSockHandle(); 167 | if ( fd > 0 ) 168 | _obj_map.AddMapObj(fd,(void*)sock); 169 | 170 | return ; 171 | } 172 | 173 | void CEPoller::DetachSocket(CEpollSocket* sock) 174 | { 175 | int fd = sock->GetSockHandle(); 176 | if ( fd > 0 ) 177 | { 178 | DelEpollIO(fd); 179 | _obj_map.DelMapObj(fd); 180 | } 181 | 182 | return ; 183 | } 184 | 185 | int CEPoller::LoopForEvent(int timeout) 186 | { 187 | int fd; 188 | int nfds; 189 | CEpollSocket* sock; 190 | unsigned ev; 191 | struct timeval prev_tm; 192 | struct timeval next_tm; 193 | long use_time_usec; 194 | gettimeofday(&prev_tm,NULL); 195 | 196 | for(;;) 197 | { 198 | nfds = epoll_wait(_epoll_fd, _events, EPOLL_FD_MAX, timeout); 199 | 200 | if (nfds < 0) 201 | { 202 | if ( errno == EINTR ) 203 | continue; 204 | 205 | memset(_err_msg,0,NET_ERRMSG_SIZE); 206 | snprintf(_err_msg,NET_ERRMSG_SIZE,"epoll-wait rtn:%d error:%s\n",nfds,strerror(errno)); 207 | return -1; 208 | } 209 | 210 | for( int i=0;iOnRecv(); 225 | else if ( ev&EPOLLOUT ) 226 | sock->OnSend(); 227 | else if ( ev&EPOLLHUP ) 228 | sock->OnClose(); 229 | else if ( ev&EPOLLERR ) 230 | sock->OnError(); 231 | else 232 | sock->OnError(); 233 | } 234 | 235 | #if 0 236 | gettimeofday(&next_tm,NULL); 237 | use_time_usec = (next_tm.tv_sec - prev_tm.tv_sec)*1000000 + 238 | (next_tm.tv_usec - prev_tm.tv_usec); 239 | 240 | if ( use_time_usec > (1000)) 241 | { 242 | CTimer::Ins()->CheckTimeOut(next_tm); 243 | CTimer::InsSpecial()->CheckTimeOut(next_tm); 244 | CTimer::Ins2()->CheckTimeOut(next_tm,2); 245 | prev_tm = next_tm; 246 | } 247 | #endif 248 | } 249 | } 250 | 251 | char * CEPoller::GetErrMsg() 252 | { 253 | return _err_msg; 254 | } 255 | 256 | int CEPoller::SetEpollIO(int fd,unsigned flag) 257 | { 258 | epoll_event ev; 259 | ev.data.fd = fd; 260 | ev.events = flag|EPOLLHUP|EPOLLERR; 261 | 262 | if ( epoll_ctl(_epoll_fd, EPOLL_CTL_MOD , fd, &ev) < 0 ) 263 | { 264 | if ( epoll_ctl(_epoll_fd, EPOLL_CTL_ADD , fd, &ev) < 0 ) 265 | { 266 | memset(_err_msg,0,NET_ERRMSG_SIZE); 267 | snprintf(_err_msg,NET_ERRMSG_SIZE,"epoll_ctl fd:%d err:%s\n",fd,strerror(errno)); 268 | return -1; 269 | } 270 | } 271 | 272 | return 0; 273 | } 274 | 275 | int CEPoller::AddEpollIO(int fd,unsigned flag) 276 | { 277 | epoll_event ev; 278 | ev.data.fd = fd; 279 | ev.events = flag; 280 | 281 | if ( epoll_ctl(_epoll_fd, EPOLL_CTL_ADD , fd, &ev) < 0 ) 282 | return -1; 283 | 284 | return 0; 285 | } 286 | 287 | int CEPoller::ModEpollIO(int fd,unsigned flag) 288 | { 289 | epoll_event ev; 290 | ev.data.fd = fd; 291 | ev.events = flag; 292 | 293 | if ( epoll_ctl(_epoll_fd, EPOLL_CTL_MOD , fd, &ev) < 0 ) 294 | { 295 | return -1; 296 | } 297 | 298 | return 0; 299 | } 300 | 301 | int CEPoller::DelEpollIO(int fd) 302 | { 303 | epoll_event ev; 304 | ev.data.fd = fd; 305 | ev.events = 0; 306 | if ( epoll_ctl(_epoll_fd, EPOLL_CTL_DEL, fd, &ev) < 0 ) 307 | return -1; 308 | 309 | return 0; 310 | } 311 | 312 | CEpollSocket::CEpollSocket() 313 | { 314 | _event_flag = false; 315 | _sock_fd = -1; 316 | _epoller = NULL; 317 | m_iLSID = 0; 318 | m_mod_ret = 0; 319 | } 320 | 321 | CEpollSocket::~CEpollSocket() 322 | { 323 | DropSocket(); 324 | } 325 | 326 | int CEpollSocket::GetSockHandle() 327 | { 328 | return _sock_fd; 329 | } 330 | 331 | int CEpollSocket::SetSockHandle(int fd) 332 | { 333 | _sock_fd = fd; 334 | _event_flag = false; 335 | 336 | return 0; 337 | } 338 | 339 | int CEpollSocket::AttachEpoller(CEPoller* epoller) 340 | { 341 | _epoller = epoller; 342 | _event_flag = false; 343 | if ( _epoller ) _epoller->AttachSocket(this); 344 | 345 | return 0; 346 | } 347 | 348 | int CEpollSocket::DetachEpoller() 349 | { 350 | if ( _epoller ) _epoller->DetachSocket(this); 351 | _epoller = NULL; 352 | 353 | return 0; 354 | } 355 | 356 | int CEpollSocket::SetEvent(unsigned event) 357 | { 358 | if ( !_epoller ) return -1; 359 | 360 | if ( _epoller->ModEpollIO(_sock_fd,event) < 0 ) 361 | return _epoller->AddEpollIO(_sock_fd,event); 362 | 363 | return 0; 364 | } 365 | 366 | int CEpollSocket::DropSocket() 367 | { 368 | if ( _sock_fd ) 369 | { 370 | DetachEpoller(); 371 | close(_sock_fd); 372 | } 373 | _sock_fd = -1; 374 | _epoller = NULL; 375 | 376 | return 0; 377 | } 378 | -------------------------------------------------------------------------------- /common/src/log.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * log.cpp 3 | * 4 | * Created on: 2014-10-4 5 | * Author: fenngwang 6 | */ 7 | 8 | 9 | #include "log.h" 10 | #include "singleton.h" 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | namespace CGI_LOG 17 | { 18 | 19 | #define LOG_CONFIG_PATH "./log/" 20 | 21 | const char * CLogFile::priority_name(int errCode) 22 | { 23 | static const string arrPriority[] = { 24 | "LM_SHUTDOWN", 25 | "LM_TRACE", 26 | "LM_DEBUG", 27 | "LM_INFO", 28 | "LM_NOTICE", 29 | "LM_WARNING", 30 | "LM_STARTUP", 31 | "LM_ERROR", 32 | "LM_CRITICAL", 33 | "LM_ALERT", 34 | "LM_EMERGENCY" 35 | "LM_UNKNOW" 36 | }; 37 | float err = log((double)errCode)/log(2.0); 38 | if (err > 10 || errCode < 0) 39 | return arrPriority[11].c_str(); 40 | return arrPriority[(int)err].c_str(); 41 | } 42 | 43 | int CLogFile::WriteLog(const char *sFile, const int iLine, const char *sFunc, int i32Level, const char * pszFormat, va_list ap) 44 | { 45 | FILE * m_pLogFile; 46 | 47 | if (m_sLogFilePath.empty()) return -2; //not initialize 48 | m_pLogFile = fopen(m_sLogFilePath.c_str(), "a+"); 49 | if (m_pLogFile == NULL) 50 | { 51 | return -1; 52 | } 53 | 54 | struct tm _tm; 55 | time_t nowtime = time(NULL); 56 | localtime_r(&nowtime, &_tm); 57 | 58 | char _pstr[20]; 59 | snprintf(_pstr, sizeof(_pstr), "%04d-%02d-%02d %02d:%02d:%02d", 60 | _tm.tm_year+1900, _tm.tm_mon+1, _tm.tm_mday, 61 | _tm.tm_hour, _tm.tm_min, _tm.tm_sec); 62 | _pstr[20] = '\0'; 63 | 64 | fprintf(m_pLogFile, "[%d,%d--%s:%d:%s] <%s> [%s]", getppid(), getpid(), sFile, iLine, sFunc, priority_name(i32Level), _pstr); 65 | vfprintf(m_pLogFile, pszFormat, ap); 66 | fprintf(m_pLogFile, "\n"); 67 | fclose(m_pLogFile); 68 | 69 | ShiftFiles(10000000, 5); 70 | return 0; 71 | } 72 | 73 | int CLogFile::ShiftFiles(long lMaxLogSize, int iMaxLogNum) 74 | { 75 | struct stat stStat; 76 | char sOldLogFileName[300]; 77 | char sNewLogFileName[300]; 78 | int i; 79 | 80 | if (stat(m_sLogFilePath.c_str(), &stStat) < 0) 81 | { 82 | return -1; 83 | } 84 | 85 | if (stStat.st_size < lMaxLogSize) 86 | { 87 | return 0; 88 | } 89 | 90 | snprintf(sNewLogFileName, sizeof(sNewLogFileName) - 1, "%s.%d", m_sLogFilePath.c_str(), iMaxLogNum-1); 91 | if (access(sNewLogFileName, F_OK) == 0) 92 | { 93 | if (remove(sNewLogFileName) < 0 ) 94 | { 95 | return -1; 96 | } 97 | } 98 | for (i = iMaxLogNum-2; i >= 0; i--) 99 | { 100 | if (i != 0) 101 | snprintf(sOldLogFileName,sizeof(sOldLogFileName)-1, "%s.%d", m_sLogFilePath.c_str(), i); 102 | else { 103 | snprintf(sOldLogFileName, sizeof(sOldLogFileName)-1,"%s", m_sLogFilePath.c_str()); 104 | } 105 | 106 | if (access(sOldLogFileName, F_OK) == 0) 107 | { 108 | snprintf(sNewLogFileName, sizeof(sNewLogFileName)-1, "%s.%d", m_sLogFilePath.c_str(), i+1); 109 | if (rename(sOldLogFileName, sNewLogFileName) < 0 ) 110 | { 111 | return -1; 112 | } 113 | } 114 | } 115 | return 0; 116 | } 117 | 118 | void CGI_Log_Init(const string & strLogName) 119 | { 120 | CLogFile * pLog = CSingleton::instance(); 121 | 122 | string path = LOG_CONFIG_PATH; 123 | if (path.empty()) 124 | { 125 | return; 126 | } 127 | 128 | string filename; 129 | size_t pos = strLogName.find_last_of('/'); 130 | if (pos == string::npos) 131 | { 132 | filename = strLogName; 133 | } 134 | else 135 | { 136 | filename = strLogName.substr(pos + 1); 137 | } 138 | pLog->SetLogPath(path + "/" + filename); 139 | } 140 | 141 | void CGI_Error_Log_Orig(const char *sFile, const int iLine, const char *sFunc, int i32Level, const char* pszFormat, ...) 142 | { 143 | // static int LOG_LEVEL = CSingleton::instance()->GetLogLevel(); 144 | // if (i32Level <= LOG_LEVEL) return; 145 | 146 | va_list ap; 147 | CLogFile * pLog= CSingleton::instance(); 148 | 149 | va_start (ap, pszFormat); 150 | pLog->WriteLog (sFile, iLine, sFunc, i32Level, pszFormat, ap); 151 | va_end (ap); 152 | } 153 | 154 | } 155 | -------------------------------------------------------------------------------- /common/src/message_process.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * message_process.cpp 3 | * 4 | * Created on: 2016年2月2日 5 | * Author: fenngwang 6 | */ 7 | #include "message_process.h" 8 | #include "log.h" 9 | #include "netserver.pb.h" 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | using namespace CGI_LOG; 15 | 16 | Message_Process::Message_Process() 17 | { 18 | sock_connect = NULL; 19 | recv_buffer_index = 0; 20 | send_buffer_need_len = 0; 21 | already_recv_len = 0; 22 | bzero(recv_buffer,MaxPacketLength); 23 | bzero(send_buffer,MaxPacketLength); 24 | } 25 | 26 | Message_Process::~Message_Process() 27 | { 28 | 29 | } 30 | 31 | int Message_Process::recv() 32 | { 33 | API_LOG_DEBUG(LM_ERROR,"enter Message_Process onRecv, ip:%s, sequence is %d", sock_connect->getIP().c_str(), sock_connect->getSequence()); 34 | already_recv_len = 0; 35 | while(1) 36 | { 37 | int ret = ::recv(sock_connect->_sock_fd,recv_buffer+recv_buffer_index,MaxPacketLength-recv_buffer_index,0); 38 | if(ret < 0) 39 | { 40 | if(errno == EWOULDBLOCK || errno == EAGAIN) // 没有数据了 41 | { 42 | return already_recv_len; 43 | } 44 | else if(errno == EINTR) 45 | { 46 | continue; 47 | } 48 | else 49 | { 50 | API_LOG_DEBUG(LM_ERROR,"recv error. ret:%d, errno:%d", ret, errno); 51 | return -1; 52 | } 53 | } 54 | else if(ret == 0) // 对方已经断掉 55 | { 56 | API_LOG_DEBUG(LM_ERROR,"recv close"); 57 | return 0; 58 | } 59 | else 60 | { 61 | recv_buffer_index += ret; 62 | already_recv_len += ret; 63 | API_LOG_DEBUG(LM_TRACE,"before process_buffer, already_recv_len:%d,recv_buffer_index:%d, ret:%d", already_recv_len,recv_buffer_index, ret); 64 | if(process_buffer(recv_buffer, recv_buffer_index) < 0) 65 | { 66 | API_LOG_DEBUG(LM_ERROR,"process_buffer failed"); 67 | return -1; 68 | } 69 | API_LOG_DEBUG(LM_TRACE,"after process_buffer, recv_buffer_index:%d", recv_buffer_index); 70 | } 71 | } 72 | return 0; 73 | } 74 | 75 | int Message_Process::send() 76 | { 77 | unsigned int send_data_len = 0; 78 | API_LOG_DEBUG(LM_ERROR,"begin send, need send %d len data", send_buffer_need_len); 79 | while(1) 80 | { 81 | int ret = ::send(sock_connect->_sock_fd, send_buffer+send_data_len, send_buffer_need_len-send_data_len, MSG_NOSIGNAL); 82 | if(ret == 0) 83 | { 84 | API_LOG_DEBUG(LM_ERROR,"send close"); 85 | return 0; 86 | } 87 | else if (ret < 0) 88 | { 89 | if((errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)) // 不算错误,继续发送 90 | { 91 | continue; 92 | } 93 | API_LOG_DEBUG(LM_ERROR,"send failed, ret:%d, errno:%d", ret, errno); 94 | return -1; 95 | } 96 | else 97 | { 98 | API_LOG_DEBUG(LM_ERROR,"send success, len:%d", ret); 99 | send_data_len+=ret; 100 | if(send_data_len >= send_buffer_need_len) // 发完了,清空数据 101 | { 102 | send_buffer_need_len = 0; 103 | bzero(send_buffer,MaxPacketLength); 104 | return send_data_len; 105 | } 106 | } 107 | } 108 | } 109 | 110 | int Message_Process::process_buffer(char *buffer, uint32_t &recv_buffer_index) 111 | { 112 | uint32_t unprocess_buffer_length = recv_buffer_index; // 未处理的缓冲区长度 113 | int start = 0; // 初始的读buffer的起点 114 | 115 | while(1) 116 | { 117 | API_LOG_DEBUG(LM_TRACE, "unprocess_buffer_length:%d, PacketHeadLength:%d", unprocess_buffer_length, PacketHeadLength); 118 | char *start_buffer = buffer+start; 119 | if(unprocess_buffer_length >= PacketHeadLength) // 长度比包头长 120 | { 121 | PacketHead header; 122 | transferBufferToPacketHead(start_buffer, header); 123 | if(header.uiPacketLen > MaxPacketLength-PacketHeadLength) // 客户端的包,包体太长 124 | { 125 | API_LOG_DEBUG(LM_ERROR, "header.uiPacketLen:%d > MaxPacketContentLength:%d", header.uiPacketLen, MaxPacketLength-PacketHeadLength); 126 | return -1; 127 | } 128 | 129 | if(unprocess_buffer_length < PacketHeadLength+header.uiPacketLen) // 没有接收完 130 | { 131 | //API_LOG_DEBUG(LM_TRACE, "length:%d < PacketHeadLength+header.uiPacketLen:%d", unprocess_buffer_length, PacketHeadLength+header.uiPacketLen); 132 | if(start > 0) // buffer中有完整的包,已经处理过,则要移动buffer 133 | { 134 | memmove(buffer, buffer+start, unprocess_buffer_length); 135 | } 136 | return 0; 137 | } 138 | else if(unprocess_buffer_length >= PacketHeadLength+header.uiPacketLen) // 已经有了一个完整的包 139 | { 140 | switch(header.cmd) 141 | { 142 | case CMD_GetUserName: 143 | { 144 | /* 145 | * 接收数据 146 | */ 147 | API_LOG_DEBUG(LM_TRACE,"recv a packet, cmd:%d", header.cmd); 148 | netserver::GetUserNameRequest request; 149 | if(!request.ParseFromArray(start_buffer+PacketHeadLength,header.uiPacketLen)) 150 | { 151 | API_LOG_DEBUG(LM_ERROR, "ParseFromArray, cmd:%d", header.cmd); 152 | return -1; 153 | } 154 | API_LOG_DEBUG(LM_TRACE,"success, userid is %d, cmd:%d",request.userid(), header.cmd); 155 | start+=PacketHeadLength+header.uiPacketLen; // 更新起始位置 156 | unprocess_buffer_length = unprocess_buffer_length - PacketHeadLength-header.uiPacketLen; // 剩余的未读缓冲区长度 157 | recv_buffer_index = unprocess_buffer_length; 158 | /* 159 | * 填充返回数据 160 | */ 161 | NetPacket resPacket; 162 | resPacket.netPacketHead.version = 1; 163 | resPacket.netPacketHead.cmd = CMD_GetUserName; 164 | resPacket.netPacketHead.serialNo = 1001; 165 | resPacket.netPacketHead.result = 0; 166 | netserver::GetUserNameResponse response; 167 | response.set_gender(1); 168 | response.set_name("fenngwang"); 169 | response.set_province("甘肃"); 170 | string strResponse; 171 | if(!response.SerializeToString(&strResponse)) 172 | { 173 | resPacket.netPacketHead.result = RetServerFailed; 174 | resPacket.netPacketHead.uiPacketLen = 0; 175 | API_LOG_DEBUG(LM_ERROR, "SerializeToString"); 176 | } 177 | else 178 | { 179 | resPacket.netPacketHead.uiPacketLen = strResponse.length(); 180 | } 181 | if(PacketHeadLength + resPacket.netPacketHead.uiPacketLen <= MaxPacketLength-send_buffer_need_len) // 发送缓冲区未满 182 | { 183 | API_LOG_DEBUG(LM_DEBUG, "write %d len data, cmd:%d", PacketHeadLength + resPacket.netPacketHead.uiPacketLen,resPacket.netPacketHead.cmd); 184 | resPacket.Encode(); 185 | memcpy(send_buffer+send_buffer_need_len, &(resPacket.netPacketHead), PacketHeadLength); 186 | memcpy(send_buffer+send_buffer_need_len+PacketHeadLength, strResponse.c_str(), strResponse.length()); 187 | send_buffer_need_len+=PacketHeadLength + strResponse.length(); 188 | sock_connect->SetEvent(FD_RECV|FD_SEND|FD_CLOSE|FD_ERROR); 189 | } 190 | else 191 | { 192 | API_LOG_DEBUG(LM_ERROR,"send buffer is full, cmd:%d", header.cmd); 193 | } 194 | 195 | break; 196 | } 197 | case CMD_SetUserName: 198 | { 199 | /* 200 | * 接收数据 201 | */ 202 | API_LOG_DEBUG(LM_TRACE," recv a packet, cmd:%d", header.cmd); 203 | netserver::SetUserNameRequest request; 204 | if(!request.ParseFromArray(start_buffer+PacketHeadLength,header.uiPacketLen)) 205 | { 206 | API_LOG_DEBUG(LM_ERROR, "ParseFromArray, cmd:%d", header.cmd); 207 | return -1; 208 | } 209 | API_LOG_DEBUG(LM_TRACE,"success, gender is %d, name is %s, province is %s",request.gender(), request.name().c_str(), request.province().c_str()); 210 | start+=PacketHeadLength+header.uiPacketLen; // 更新起始位置 211 | unprocess_buffer_length = unprocess_buffer_length - PacketHeadLength-header.uiPacketLen; // 剩余的未读缓冲区长度 212 | recv_buffer_index = unprocess_buffer_length; 213 | /* 214 | * 填充返回数据 215 | */ 216 | NetPacket resPacket; 217 | resPacket.netPacketHead.version = 1; 218 | resPacket.netPacketHead.cmd = CMD_SetUserName; 219 | resPacket.netPacketHead.serialNo = 1001; 220 | resPacket.netPacketHead.result = 0; 221 | resPacket.netPacketHead.uiPacketLen = 0; 222 | if(PacketHeadLength <= MaxPacketLength-send_buffer_need_len) // 发送缓冲区未满 223 | { 224 | API_LOG_DEBUG(LM_DEBUG, "write %d len data, cmd:%d", PacketHeadLength,resPacket.netPacketHead.cmd); 225 | sock_connect->SetEvent(FD_RECV|FD_SEND|FD_CLOSE|FD_ERROR); 226 | resPacket.Encode(); 227 | memcpy(send_buffer+send_buffer_need_len, &(resPacket.netPacketHead), PacketHeadLength); 228 | send_buffer_need_len+=PacketHeadLength; 229 | } 230 | else 231 | { 232 | API_LOG_DEBUG(LM_ERROR,"send buffer is full, cmd:%d", header.cmd); 233 | } 234 | break; 235 | } 236 | default: 237 | API_LOG_DEBUG(LM_ERROR,"recv a undefined packet, cmd:%d", header.cmd); 238 | start+=PacketHeadLength+header.uiPacketLen; // 更新起始位置 239 | unprocess_buffer_length = unprocess_buffer_length - PacketHeadLength-header.uiPacketLen; // 剩余的未读缓冲区长度 240 | recv_buffer_index = unprocess_buffer_length; 241 | /* 242 | * 填充返回数据 243 | */ 244 | NetPacket resPacket; 245 | resPacket.netPacketHead.version = 1; 246 | resPacket.netPacketHead.cmd = CMD_GetUserName; 247 | resPacket.netPacketHead.serialNo = 1001; 248 | resPacket.netPacketHead.result = -1; 249 | resPacket.netPacketHead.uiPacketLen = 0; 250 | if(PacketHeadLength <= MaxPacketLength-send_buffer_need_len) // 发送缓冲区未满 251 | { 252 | API_LOG_DEBUG(LM_DEBUG, "write %d len data, cmd:%d", PacketHeadLength,resPacket.netPacketHead.cmd); 253 | sock_connect->SetEvent(FD_RECV|FD_SEND|FD_CLOSE|FD_ERROR); 254 | resPacket.Encode(); 255 | memcpy(send_buffer+send_buffer_need_len, &(resPacket.netPacketHead), PacketHeadLength); 256 | send_buffer_need_len+=PacketHeadLength; 257 | } 258 | else 259 | { 260 | API_LOG_DEBUG(LM_ERROR,"send buffer is full, cmd:%d", header.cmd); 261 | } 262 | resPacket.Encode(); 263 | break; 264 | } 265 | } 266 | } 267 | else // 包头都不够 268 | { 269 | API_LOG_DEBUG(LM_TRACE, "unprocess_buffer_length:%d < PacketHeadLength:%d", unprocess_buffer_length,PacketHeadLength); 270 | if(start > 0) // buffer中有完整的包,已经处理过,则要移动buffer 271 | { 272 | memmove(buffer, buffer+start, unprocess_buffer_length); 273 | } 274 | return 0; 275 | } 276 | } 277 | return 0; 278 | } 279 | -------------------------------------------------------------------------------- /common/src/netserver.pb.cc: -------------------------------------------------------------------------------- 1 | // Generated by the protocol buffer compiler. DO NOT EDIT! 2 | 3 | #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION 4 | #include "netserver.pb.h" 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | // @@protoc_insertion_point(includes) 15 | 16 | namespace netserver { 17 | 18 | namespace { 19 | 20 | const ::google::protobuf::Descriptor* GetUserNameRequest_descriptor_ = NULL; 21 | const ::google::protobuf::internal::GeneratedMessageReflection* 22 | GetUserNameRequest_reflection_ = NULL; 23 | const ::google::protobuf::Descriptor* GetUserNameResponse_descriptor_ = NULL; 24 | const ::google::protobuf::internal::GeneratedMessageReflection* 25 | GetUserNameResponse_reflection_ = NULL; 26 | const ::google::protobuf::Descriptor* SetUserNameRequest_descriptor_ = NULL; 27 | const ::google::protobuf::internal::GeneratedMessageReflection* 28 | SetUserNameRequest_reflection_ = NULL; 29 | 30 | } // namespace 31 | 32 | 33 | void protobuf_AssignDesc_netserver_2eproto() { 34 | protobuf_AddDesc_netserver_2eproto(); 35 | const ::google::protobuf::FileDescriptor* file = 36 | ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( 37 | "netserver.proto"); 38 | GOOGLE_CHECK(file != NULL); 39 | GetUserNameRequest_descriptor_ = file->message_type(0); 40 | static const int GetUserNameRequest_offsets_[1] = { 41 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GetUserNameRequest, userid_), 42 | }; 43 | GetUserNameRequest_reflection_ = 44 | new ::google::protobuf::internal::GeneratedMessageReflection( 45 | GetUserNameRequest_descriptor_, 46 | GetUserNameRequest::default_instance_, 47 | GetUserNameRequest_offsets_, 48 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GetUserNameRequest, _has_bits_[0]), 49 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GetUserNameRequest, _unknown_fields_), 50 | -1, 51 | ::google::protobuf::DescriptorPool::generated_pool(), 52 | ::google::protobuf::MessageFactory::generated_factory(), 53 | sizeof(GetUserNameRequest)); 54 | GetUserNameResponse_descriptor_ = file->message_type(1); 55 | static const int GetUserNameResponse_offsets_[3] = { 56 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GetUserNameResponse, gender_), 57 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GetUserNameResponse, name_), 58 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GetUserNameResponse, province_), 59 | }; 60 | GetUserNameResponse_reflection_ = 61 | new ::google::protobuf::internal::GeneratedMessageReflection( 62 | GetUserNameResponse_descriptor_, 63 | GetUserNameResponse::default_instance_, 64 | GetUserNameResponse_offsets_, 65 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GetUserNameResponse, _has_bits_[0]), 66 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GetUserNameResponse, _unknown_fields_), 67 | -1, 68 | ::google::protobuf::DescriptorPool::generated_pool(), 69 | ::google::protobuf::MessageFactory::generated_factory(), 70 | sizeof(GetUserNameResponse)); 71 | SetUserNameRequest_descriptor_ = file->message_type(2); 72 | static const int SetUserNameRequest_offsets_[3] = { 73 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SetUserNameRequest, gender_), 74 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SetUserNameRequest, name_), 75 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SetUserNameRequest, province_), 76 | }; 77 | SetUserNameRequest_reflection_ = 78 | new ::google::protobuf::internal::GeneratedMessageReflection( 79 | SetUserNameRequest_descriptor_, 80 | SetUserNameRequest::default_instance_, 81 | SetUserNameRequest_offsets_, 82 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SetUserNameRequest, _has_bits_[0]), 83 | GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SetUserNameRequest, _unknown_fields_), 84 | -1, 85 | ::google::protobuf::DescriptorPool::generated_pool(), 86 | ::google::protobuf::MessageFactory::generated_factory(), 87 | sizeof(SetUserNameRequest)); 88 | } 89 | 90 | namespace { 91 | 92 | GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); 93 | inline void protobuf_AssignDescriptorsOnce() { 94 | ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, 95 | &protobuf_AssignDesc_netserver_2eproto); 96 | } 97 | 98 | void protobuf_RegisterTypes(const ::std::string&) { 99 | protobuf_AssignDescriptorsOnce(); 100 | ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( 101 | GetUserNameRequest_descriptor_, &GetUserNameRequest::default_instance()); 102 | ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( 103 | GetUserNameResponse_descriptor_, &GetUserNameResponse::default_instance()); 104 | ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( 105 | SetUserNameRequest_descriptor_, &SetUserNameRequest::default_instance()); 106 | } 107 | 108 | } // namespace 109 | 110 | void protobuf_ShutdownFile_netserver_2eproto() { 111 | delete GetUserNameRequest::default_instance_; 112 | delete GetUserNameRequest_reflection_; 113 | delete GetUserNameResponse::default_instance_; 114 | delete GetUserNameResponse_reflection_; 115 | delete SetUserNameRequest::default_instance_; 116 | delete SetUserNameRequest_reflection_; 117 | } 118 | 119 | void protobuf_AddDesc_netserver_2eproto() { 120 | static bool already_here = false; 121 | if (already_here) return; 122 | already_here = true; 123 | GOOGLE_PROTOBUF_VERIFY_VERSION; 124 | 125 | ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( 126 | "\n\017netserver.proto\022\tnetserver\"$\n\022GetUserN" 127 | "ameRequest\022\016\n\006userId\030\001 \002(\005\"E\n\023GetUserNam" 128 | "eResponse\022\016\n\006gender\030\001 \002(\005\022\014\n\004name\030\002 \002(\t\022" 129 | "\020\n\010province\030\003 \001(\t\"D\n\022SetUserNameRequest\022" 130 | "\016\n\006gender\030\001 \002(\005\022\014\n\004name\030\002 \002(\t\022\020\n\010provinc" 131 | "e\030\003 \001(\t", 207); 132 | ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( 133 | "netserver.proto", &protobuf_RegisterTypes); 134 | GetUserNameRequest::default_instance_ = new GetUserNameRequest(); 135 | GetUserNameResponse::default_instance_ = new GetUserNameResponse(); 136 | SetUserNameRequest::default_instance_ = new SetUserNameRequest(); 137 | GetUserNameRequest::default_instance_->InitAsDefaultInstance(); 138 | GetUserNameResponse::default_instance_->InitAsDefaultInstance(); 139 | SetUserNameRequest::default_instance_->InitAsDefaultInstance(); 140 | ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_netserver_2eproto); 141 | } 142 | 143 | // Force AddDescriptors() to be called at static initialization time. 144 | struct StaticDescriptorInitializer_netserver_2eproto { 145 | StaticDescriptorInitializer_netserver_2eproto() { 146 | protobuf_AddDesc_netserver_2eproto(); 147 | } 148 | } static_descriptor_initializer_netserver_2eproto_; 149 | 150 | 151 | // =================================================================== 152 | 153 | #ifndef _MSC_VER 154 | const int GetUserNameRequest::kUserIdFieldNumber; 155 | #endif // !_MSC_VER 156 | 157 | GetUserNameRequest::GetUserNameRequest() 158 | : ::google::protobuf::Message() { 159 | SharedCtor(); 160 | } 161 | 162 | void GetUserNameRequest::InitAsDefaultInstance() { 163 | } 164 | 165 | GetUserNameRequest::GetUserNameRequest(const GetUserNameRequest& from) 166 | : ::google::protobuf::Message() { 167 | SharedCtor(); 168 | MergeFrom(from); 169 | } 170 | 171 | void GetUserNameRequest::SharedCtor() { 172 | _cached_size_ = 0; 173 | userid_ = 0; 174 | ::memset(_has_bits_, 0, sizeof(_has_bits_)); 175 | } 176 | 177 | GetUserNameRequest::~GetUserNameRequest() { 178 | SharedDtor(); 179 | } 180 | 181 | void GetUserNameRequest::SharedDtor() { 182 | if (this != default_instance_) { 183 | } 184 | } 185 | 186 | void GetUserNameRequest::SetCachedSize(int size) const { 187 | GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); 188 | _cached_size_ = size; 189 | GOOGLE_SAFE_CONCURRENT_WRITES_END(); 190 | } 191 | const ::google::protobuf::Descriptor* GetUserNameRequest::descriptor() { 192 | protobuf_AssignDescriptorsOnce(); 193 | return GetUserNameRequest_descriptor_; 194 | } 195 | 196 | const GetUserNameRequest& GetUserNameRequest::default_instance() { 197 | if (default_instance_ == NULL) protobuf_AddDesc_netserver_2eproto(); return *default_instance_; 198 | } 199 | 200 | GetUserNameRequest* GetUserNameRequest::default_instance_ = NULL; 201 | 202 | GetUserNameRequest* GetUserNameRequest::New() const { 203 | return new GetUserNameRequest; 204 | } 205 | 206 | void GetUserNameRequest::Clear() { 207 | if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { 208 | userid_ = 0; 209 | } 210 | ::memset(_has_bits_, 0, sizeof(_has_bits_)); 211 | mutable_unknown_fields()->Clear(); 212 | } 213 | 214 | bool GetUserNameRequest::MergePartialFromCodedStream( 215 | ::google::protobuf::io::CodedInputStream* input) { 216 | #define DO_(EXPRESSION) if (!(EXPRESSION)) return false 217 | ::google::protobuf::uint32 tag; 218 | while ((tag = input->ReadTag()) != 0) { 219 | switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { 220 | // required int32 userId = 1; 221 | case 1: { 222 | if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == 223 | ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { 224 | DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< 225 | ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( 226 | input, &userid_))); 227 | set_has_userid(); 228 | } else { 229 | goto handle_uninterpreted; 230 | } 231 | if (input->ExpectAtEnd()) return true; 232 | break; 233 | } 234 | 235 | default: { 236 | handle_uninterpreted: 237 | if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == 238 | ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { 239 | return true; 240 | } 241 | DO_(::google::protobuf::internal::WireFormat::SkipField( 242 | input, tag, mutable_unknown_fields())); 243 | break; 244 | } 245 | } 246 | } 247 | return true; 248 | #undef DO_ 249 | } 250 | 251 | void GetUserNameRequest::SerializeWithCachedSizes( 252 | ::google::protobuf::io::CodedOutputStream* output) const { 253 | // required int32 userId = 1; 254 | if (has_userid()) { 255 | ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->userid(), output); 256 | } 257 | 258 | if (!unknown_fields().empty()) { 259 | ::google::protobuf::internal::WireFormat::SerializeUnknownFields( 260 | unknown_fields(), output); 261 | } 262 | } 263 | 264 | ::google::protobuf::uint8* GetUserNameRequest::SerializeWithCachedSizesToArray( 265 | ::google::protobuf::uint8* target) const { 266 | // required int32 userId = 1; 267 | if (has_userid()) { 268 | target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->userid(), target); 269 | } 270 | 271 | if (!unknown_fields().empty()) { 272 | target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( 273 | unknown_fields(), target); 274 | } 275 | return target; 276 | } 277 | 278 | int GetUserNameRequest::ByteSize() const { 279 | int total_size = 0; 280 | 281 | if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { 282 | // required int32 userId = 1; 283 | if (has_userid()) { 284 | total_size += 1 + 285 | ::google::protobuf::internal::WireFormatLite::Int32Size( 286 | this->userid()); 287 | } 288 | 289 | } 290 | if (!unknown_fields().empty()) { 291 | total_size += 292 | ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( 293 | unknown_fields()); 294 | } 295 | GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); 296 | _cached_size_ = total_size; 297 | GOOGLE_SAFE_CONCURRENT_WRITES_END(); 298 | return total_size; 299 | } 300 | 301 | void GetUserNameRequest::MergeFrom(const ::google::protobuf::Message& from) { 302 | GOOGLE_CHECK_NE(&from, this); 303 | const GetUserNameRequest* source = 304 | ::google::protobuf::internal::dynamic_cast_if_available( 305 | &from); 306 | if (source == NULL) { 307 | ::google::protobuf::internal::ReflectionOps::Merge(from, this); 308 | } else { 309 | MergeFrom(*source); 310 | } 311 | } 312 | 313 | void GetUserNameRequest::MergeFrom(const GetUserNameRequest& from) { 314 | GOOGLE_CHECK_NE(&from, this); 315 | if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { 316 | if (from.has_userid()) { 317 | set_userid(from.userid()); 318 | } 319 | } 320 | mutable_unknown_fields()->MergeFrom(from.unknown_fields()); 321 | } 322 | 323 | void GetUserNameRequest::CopyFrom(const ::google::protobuf::Message& from) { 324 | if (&from == this) return; 325 | Clear(); 326 | MergeFrom(from); 327 | } 328 | 329 | void GetUserNameRequest::CopyFrom(const GetUserNameRequest& from) { 330 | if (&from == this) return; 331 | Clear(); 332 | MergeFrom(from); 333 | } 334 | 335 | bool GetUserNameRequest::IsInitialized() const { 336 | if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; 337 | 338 | return true; 339 | } 340 | 341 | void GetUserNameRequest::Swap(GetUserNameRequest* other) { 342 | if (other != this) { 343 | std::swap(userid_, other->userid_); 344 | std::swap(_has_bits_[0], other->_has_bits_[0]); 345 | _unknown_fields_.Swap(&other->_unknown_fields_); 346 | std::swap(_cached_size_, other->_cached_size_); 347 | } 348 | } 349 | 350 | ::google::protobuf::Metadata GetUserNameRequest::GetMetadata() const { 351 | protobuf_AssignDescriptorsOnce(); 352 | ::google::protobuf::Metadata metadata; 353 | metadata.descriptor = GetUserNameRequest_descriptor_; 354 | metadata.reflection = GetUserNameRequest_reflection_; 355 | return metadata; 356 | } 357 | 358 | 359 | // =================================================================== 360 | 361 | #ifndef _MSC_VER 362 | const int GetUserNameResponse::kGenderFieldNumber; 363 | const int GetUserNameResponse::kNameFieldNumber; 364 | const int GetUserNameResponse::kProvinceFieldNumber; 365 | #endif // !_MSC_VER 366 | 367 | GetUserNameResponse::GetUserNameResponse() 368 | : ::google::protobuf::Message() { 369 | SharedCtor(); 370 | } 371 | 372 | void GetUserNameResponse::InitAsDefaultInstance() { 373 | } 374 | 375 | GetUserNameResponse::GetUserNameResponse(const GetUserNameResponse& from) 376 | : ::google::protobuf::Message() { 377 | SharedCtor(); 378 | MergeFrom(from); 379 | } 380 | 381 | void GetUserNameResponse::SharedCtor() { 382 | _cached_size_ = 0; 383 | gender_ = 0; 384 | name_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); 385 | province_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); 386 | ::memset(_has_bits_, 0, sizeof(_has_bits_)); 387 | } 388 | 389 | GetUserNameResponse::~GetUserNameResponse() { 390 | SharedDtor(); 391 | } 392 | 393 | void GetUserNameResponse::SharedDtor() { 394 | if (name_ != &::google::protobuf::internal::kEmptyString) { 395 | delete name_; 396 | } 397 | if (province_ != &::google::protobuf::internal::kEmptyString) { 398 | delete province_; 399 | } 400 | if (this != default_instance_) { 401 | } 402 | } 403 | 404 | void GetUserNameResponse::SetCachedSize(int size) const { 405 | GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); 406 | _cached_size_ = size; 407 | GOOGLE_SAFE_CONCURRENT_WRITES_END(); 408 | } 409 | const ::google::protobuf::Descriptor* GetUserNameResponse::descriptor() { 410 | protobuf_AssignDescriptorsOnce(); 411 | return GetUserNameResponse_descriptor_; 412 | } 413 | 414 | const GetUserNameResponse& GetUserNameResponse::default_instance() { 415 | if (default_instance_ == NULL) protobuf_AddDesc_netserver_2eproto(); return *default_instance_; 416 | } 417 | 418 | GetUserNameResponse* GetUserNameResponse::default_instance_ = NULL; 419 | 420 | GetUserNameResponse* GetUserNameResponse::New() const { 421 | return new GetUserNameResponse; 422 | } 423 | 424 | void GetUserNameResponse::Clear() { 425 | if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { 426 | gender_ = 0; 427 | if (has_name()) { 428 | if (name_ != &::google::protobuf::internal::kEmptyString) { 429 | name_->clear(); 430 | } 431 | } 432 | if (has_province()) { 433 | if (province_ != &::google::protobuf::internal::kEmptyString) { 434 | province_->clear(); 435 | } 436 | } 437 | } 438 | ::memset(_has_bits_, 0, sizeof(_has_bits_)); 439 | mutable_unknown_fields()->Clear(); 440 | } 441 | 442 | bool GetUserNameResponse::MergePartialFromCodedStream( 443 | ::google::protobuf::io::CodedInputStream* input) { 444 | #define DO_(EXPRESSION) if (!(EXPRESSION)) return false 445 | ::google::protobuf::uint32 tag; 446 | while ((tag = input->ReadTag()) != 0) { 447 | switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { 448 | // required int32 gender = 1; 449 | case 1: { 450 | if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == 451 | ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { 452 | DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< 453 | ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( 454 | input, &gender_))); 455 | set_has_gender(); 456 | } else { 457 | goto handle_uninterpreted; 458 | } 459 | if (input->ExpectTag(18)) goto parse_name; 460 | break; 461 | } 462 | 463 | // required string name = 2; 464 | case 2: { 465 | if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == 466 | ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { 467 | parse_name: 468 | DO_(::google::protobuf::internal::WireFormatLite::ReadString( 469 | input, this->mutable_name())); 470 | ::google::protobuf::internal::WireFormat::VerifyUTF8String( 471 | this->name().data(), this->name().length(), 472 | ::google::protobuf::internal::WireFormat::PARSE); 473 | } else { 474 | goto handle_uninterpreted; 475 | } 476 | if (input->ExpectTag(26)) goto parse_province; 477 | break; 478 | } 479 | 480 | // optional string province = 3; 481 | case 3: { 482 | if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == 483 | ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { 484 | parse_province: 485 | DO_(::google::protobuf::internal::WireFormatLite::ReadString( 486 | input, this->mutable_province())); 487 | ::google::protobuf::internal::WireFormat::VerifyUTF8String( 488 | this->province().data(), this->province().length(), 489 | ::google::protobuf::internal::WireFormat::PARSE); 490 | } else { 491 | goto handle_uninterpreted; 492 | } 493 | if (input->ExpectAtEnd()) return true; 494 | break; 495 | } 496 | 497 | default: { 498 | handle_uninterpreted: 499 | if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == 500 | ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { 501 | return true; 502 | } 503 | DO_(::google::protobuf::internal::WireFormat::SkipField( 504 | input, tag, mutable_unknown_fields())); 505 | break; 506 | } 507 | } 508 | } 509 | return true; 510 | #undef DO_ 511 | } 512 | 513 | void GetUserNameResponse::SerializeWithCachedSizes( 514 | ::google::protobuf::io::CodedOutputStream* output) const { 515 | // required int32 gender = 1; 516 | if (has_gender()) { 517 | ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->gender(), output); 518 | } 519 | 520 | // required string name = 2; 521 | if (has_name()) { 522 | ::google::protobuf::internal::WireFormat::VerifyUTF8String( 523 | this->name().data(), this->name().length(), 524 | ::google::protobuf::internal::WireFormat::SERIALIZE); 525 | ::google::protobuf::internal::WireFormatLite::WriteString( 526 | 2, this->name(), output); 527 | } 528 | 529 | // optional string province = 3; 530 | if (has_province()) { 531 | ::google::protobuf::internal::WireFormat::VerifyUTF8String( 532 | this->province().data(), this->province().length(), 533 | ::google::protobuf::internal::WireFormat::SERIALIZE); 534 | ::google::protobuf::internal::WireFormatLite::WriteString( 535 | 3, this->province(), output); 536 | } 537 | 538 | if (!unknown_fields().empty()) { 539 | ::google::protobuf::internal::WireFormat::SerializeUnknownFields( 540 | unknown_fields(), output); 541 | } 542 | } 543 | 544 | ::google::protobuf::uint8* GetUserNameResponse::SerializeWithCachedSizesToArray( 545 | ::google::protobuf::uint8* target) const { 546 | // required int32 gender = 1; 547 | if (has_gender()) { 548 | target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->gender(), target); 549 | } 550 | 551 | // required string name = 2; 552 | if (has_name()) { 553 | ::google::protobuf::internal::WireFormat::VerifyUTF8String( 554 | this->name().data(), this->name().length(), 555 | ::google::protobuf::internal::WireFormat::SERIALIZE); 556 | target = 557 | ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 558 | 2, this->name(), target); 559 | } 560 | 561 | // optional string province = 3; 562 | if (has_province()) { 563 | ::google::protobuf::internal::WireFormat::VerifyUTF8String( 564 | this->province().data(), this->province().length(), 565 | ::google::protobuf::internal::WireFormat::SERIALIZE); 566 | target = 567 | ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 568 | 3, this->province(), target); 569 | } 570 | 571 | if (!unknown_fields().empty()) { 572 | target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( 573 | unknown_fields(), target); 574 | } 575 | return target; 576 | } 577 | 578 | int GetUserNameResponse::ByteSize() const { 579 | int total_size = 0; 580 | 581 | if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { 582 | // required int32 gender = 1; 583 | if (has_gender()) { 584 | total_size += 1 + 585 | ::google::protobuf::internal::WireFormatLite::Int32Size( 586 | this->gender()); 587 | } 588 | 589 | // required string name = 2; 590 | if (has_name()) { 591 | total_size += 1 + 592 | ::google::protobuf::internal::WireFormatLite::StringSize( 593 | this->name()); 594 | } 595 | 596 | // optional string province = 3; 597 | if (has_province()) { 598 | total_size += 1 + 599 | ::google::protobuf::internal::WireFormatLite::StringSize( 600 | this->province()); 601 | } 602 | 603 | } 604 | if (!unknown_fields().empty()) { 605 | total_size += 606 | ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( 607 | unknown_fields()); 608 | } 609 | GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); 610 | _cached_size_ = total_size; 611 | GOOGLE_SAFE_CONCURRENT_WRITES_END(); 612 | return total_size; 613 | } 614 | 615 | void GetUserNameResponse::MergeFrom(const ::google::protobuf::Message& from) { 616 | GOOGLE_CHECK_NE(&from, this); 617 | const GetUserNameResponse* source = 618 | ::google::protobuf::internal::dynamic_cast_if_available( 619 | &from); 620 | if (source == NULL) { 621 | ::google::protobuf::internal::ReflectionOps::Merge(from, this); 622 | } else { 623 | MergeFrom(*source); 624 | } 625 | } 626 | 627 | void GetUserNameResponse::MergeFrom(const GetUserNameResponse& from) { 628 | GOOGLE_CHECK_NE(&from, this); 629 | if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { 630 | if (from.has_gender()) { 631 | set_gender(from.gender()); 632 | } 633 | if (from.has_name()) { 634 | set_name(from.name()); 635 | } 636 | if (from.has_province()) { 637 | set_province(from.province()); 638 | } 639 | } 640 | mutable_unknown_fields()->MergeFrom(from.unknown_fields()); 641 | } 642 | 643 | void GetUserNameResponse::CopyFrom(const ::google::protobuf::Message& from) { 644 | if (&from == this) return; 645 | Clear(); 646 | MergeFrom(from); 647 | } 648 | 649 | void GetUserNameResponse::CopyFrom(const GetUserNameResponse& from) { 650 | if (&from == this) return; 651 | Clear(); 652 | MergeFrom(from); 653 | } 654 | 655 | bool GetUserNameResponse::IsInitialized() const { 656 | if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; 657 | 658 | return true; 659 | } 660 | 661 | void GetUserNameResponse::Swap(GetUserNameResponse* other) { 662 | if (other != this) { 663 | std::swap(gender_, other->gender_); 664 | std::swap(name_, other->name_); 665 | std::swap(province_, other->province_); 666 | std::swap(_has_bits_[0], other->_has_bits_[0]); 667 | _unknown_fields_.Swap(&other->_unknown_fields_); 668 | std::swap(_cached_size_, other->_cached_size_); 669 | } 670 | } 671 | 672 | ::google::protobuf::Metadata GetUserNameResponse::GetMetadata() const { 673 | protobuf_AssignDescriptorsOnce(); 674 | ::google::protobuf::Metadata metadata; 675 | metadata.descriptor = GetUserNameResponse_descriptor_; 676 | metadata.reflection = GetUserNameResponse_reflection_; 677 | return metadata; 678 | } 679 | 680 | 681 | // =================================================================== 682 | 683 | #ifndef _MSC_VER 684 | const int SetUserNameRequest::kGenderFieldNumber; 685 | const int SetUserNameRequest::kNameFieldNumber; 686 | const int SetUserNameRequest::kProvinceFieldNumber; 687 | #endif // !_MSC_VER 688 | 689 | SetUserNameRequest::SetUserNameRequest() 690 | : ::google::protobuf::Message() { 691 | SharedCtor(); 692 | } 693 | 694 | void SetUserNameRequest::InitAsDefaultInstance() { 695 | } 696 | 697 | SetUserNameRequest::SetUserNameRequest(const SetUserNameRequest& from) 698 | : ::google::protobuf::Message() { 699 | SharedCtor(); 700 | MergeFrom(from); 701 | } 702 | 703 | void SetUserNameRequest::SharedCtor() { 704 | _cached_size_ = 0; 705 | gender_ = 0; 706 | name_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); 707 | province_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); 708 | ::memset(_has_bits_, 0, sizeof(_has_bits_)); 709 | } 710 | 711 | SetUserNameRequest::~SetUserNameRequest() { 712 | SharedDtor(); 713 | } 714 | 715 | void SetUserNameRequest::SharedDtor() { 716 | if (name_ != &::google::protobuf::internal::kEmptyString) { 717 | delete name_; 718 | } 719 | if (province_ != &::google::protobuf::internal::kEmptyString) { 720 | delete province_; 721 | } 722 | if (this != default_instance_) { 723 | } 724 | } 725 | 726 | void SetUserNameRequest::SetCachedSize(int size) const { 727 | GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); 728 | _cached_size_ = size; 729 | GOOGLE_SAFE_CONCURRENT_WRITES_END(); 730 | } 731 | const ::google::protobuf::Descriptor* SetUserNameRequest::descriptor() { 732 | protobuf_AssignDescriptorsOnce(); 733 | return SetUserNameRequest_descriptor_; 734 | } 735 | 736 | const SetUserNameRequest& SetUserNameRequest::default_instance() { 737 | if (default_instance_ == NULL) protobuf_AddDesc_netserver_2eproto(); return *default_instance_; 738 | } 739 | 740 | SetUserNameRequest* SetUserNameRequest::default_instance_ = NULL; 741 | 742 | SetUserNameRequest* SetUserNameRequest::New() const { 743 | return new SetUserNameRequest; 744 | } 745 | 746 | void SetUserNameRequest::Clear() { 747 | if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { 748 | gender_ = 0; 749 | if (has_name()) { 750 | if (name_ != &::google::protobuf::internal::kEmptyString) { 751 | name_->clear(); 752 | } 753 | } 754 | if (has_province()) { 755 | if (province_ != &::google::protobuf::internal::kEmptyString) { 756 | province_->clear(); 757 | } 758 | } 759 | } 760 | ::memset(_has_bits_, 0, sizeof(_has_bits_)); 761 | mutable_unknown_fields()->Clear(); 762 | } 763 | 764 | bool SetUserNameRequest::MergePartialFromCodedStream( 765 | ::google::protobuf::io::CodedInputStream* input) { 766 | #define DO_(EXPRESSION) if (!(EXPRESSION)) return false 767 | ::google::protobuf::uint32 tag; 768 | while ((tag = input->ReadTag()) != 0) { 769 | switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { 770 | // required int32 gender = 1; 771 | case 1: { 772 | if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == 773 | ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { 774 | DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< 775 | ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( 776 | input, &gender_))); 777 | set_has_gender(); 778 | } else { 779 | goto handle_uninterpreted; 780 | } 781 | if (input->ExpectTag(18)) goto parse_name; 782 | break; 783 | } 784 | 785 | // required string name = 2; 786 | case 2: { 787 | if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == 788 | ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { 789 | parse_name: 790 | DO_(::google::protobuf::internal::WireFormatLite::ReadString( 791 | input, this->mutable_name())); 792 | ::google::protobuf::internal::WireFormat::VerifyUTF8String( 793 | this->name().data(), this->name().length(), 794 | ::google::protobuf::internal::WireFormat::PARSE); 795 | } else { 796 | goto handle_uninterpreted; 797 | } 798 | if (input->ExpectTag(26)) goto parse_province; 799 | break; 800 | } 801 | 802 | // optional string province = 3; 803 | case 3: { 804 | if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == 805 | ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { 806 | parse_province: 807 | DO_(::google::protobuf::internal::WireFormatLite::ReadString( 808 | input, this->mutable_province())); 809 | ::google::protobuf::internal::WireFormat::VerifyUTF8String( 810 | this->province().data(), this->province().length(), 811 | ::google::protobuf::internal::WireFormat::PARSE); 812 | } else { 813 | goto handle_uninterpreted; 814 | } 815 | if (input->ExpectAtEnd()) return true; 816 | break; 817 | } 818 | 819 | default: { 820 | handle_uninterpreted: 821 | if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == 822 | ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { 823 | return true; 824 | } 825 | DO_(::google::protobuf::internal::WireFormat::SkipField( 826 | input, tag, mutable_unknown_fields())); 827 | break; 828 | } 829 | } 830 | } 831 | return true; 832 | #undef DO_ 833 | } 834 | 835 | void SetUserNameRequest::SerializeWithCachedSizes( 836 | ::google::protobuf::io::CodedOutputStream* output) const { 837 | // required int32 gender = 1; 838 | if (has_gender()) { 839 | ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->gender(), output); 840 | } 841 | 842 | // required string name = 2; 843 | if (has_name()) { 844 | ::google::protobuf::internal::WireFormat::VerifyUTF8String( 845 | this->name().data(), this->name().length(), 846 | ::google::protobuf::internal::WireFormat::SERIALIZE); 847 | ::google::protobuf::internal::WireFormatLite::WriteString( 848 | 2, this->name(), output); 849 | } 850 | 851 | // optional string province = 3; 852 | if (has_province()) { 853 | ::google::protobuf::internal::WireFormat::VerifyUTF8String( 854 | this->province().data(), this->province().length(), 855 | ::google::protobuf::internal::WireFormat::SERIALIZE); 856 | ::google::protobuf::internal::WireFormatLite::WriteString( 857 | 3, this->province(), output); 858 | } 859 | 860 | if (!unknown_fields().empty()) { 861 | ::google::protobuf::internal::WireFormat::SerializeUnknownFields( 862 | unknown_fields(), output); 863 | } 864 | } 865 | 866 | ::google::protobuf::uint8* SetUserNameRequest::SerializeWithCachedSizesToArray( 867 | ::google::protobuf::uint8* target) const { 868 | // required int32 gender = 1; 869 | if (has_gender()) { 870 | target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->gender(), target); 871 | } 872 | 873 | // required string name = 2; 874 | if (has_name()) { 875 | ::google::protobuf::internal::WireFormat::VerifyUTF8String( 876 | this->name().data(), this->name().length(), 877 | ::google::protobuf::internal::WireFormat::SERIALIZE); 878 | target = 879 | ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 880 | 2, this->name(), target); 881 | } 882 | 883 | // optional string province = 3; 884 | if (has_province()) { 885 | ::google::protobuf::internal::WireFormat::VerifyUTF8String( 886 | this->province().data(), this->province().length(), 887 | ::google::protobuf::internal::WireFormat::SERIALIZE); 888 | target = 889 | ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 890 | 3, this->province(), target); 891 | } 892 | 893 | if (!unknown_fields().empty()) { 894 | target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( 895 | unknown_fields(), target); 896 | } 897 | return target; 898 | } 899 | 900 | int SetUserNameRequest::ByteSize() const { 901 | int total_size = 0; 902 | 903 | if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { 904 | // required int32 gender = 1; 905 | if (has_gender()) { 906 | total_size += 1 + 907 | ::google::protobuf::internal::WireFormatLite::Int32Size( 908 | this->gender()); 909 | } 910 | 911 | // required string name = 2; 912 | if (has_name()) { 913 | total_size += 1 + 914 | ::google::protobuf::internal::WireFormatLite::StringSize( 915 | this->name()); 916 | } 917 | 918 | // optional string province = 3; 919 | if (has_province()) { 920 | total_size += 1 + 921 | ::google::protobuf::internal::WireFormatLite::StringSize( 922 | this->province()); 923 | } 924 | 925 | } 926 | if (!unknown_fields().empty()) { 927 | total_size += 928 | ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( 929 | unknown_fields()); 930 | } 931 | GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); 932 | _cached_size_ = total_size; 933 | GOOGLE_SAFE_CONCURRENT_WRITES_END(); 934 | return total_size; 935 | } 936 | 937 | void SetUserNameRequest::MergeFrom(const ::google::protobuf::Message& from) { 938 | GOOGLE_CHECK_NE(&from, this); 939 | const SetUserNameRequest* source = 940 | ::google::protobuf::internal::dynamic_cast_if_available( 941 | &from); 942 | if (source == NULL) { 943 | ::google::protobuf::internal::ReflectionOps::Merge(from, this); 944 | } else { 945 | MergeFrom(*source); 946 | } 947 | } 948 | 949 | void SetUserNameRequest::MergeFrom(const SetUserNameRequest& from) { 950 | GOOGLE_CHECK_NE(&from, this); 951 | if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { 952 | if (from.has_gender()) { 953 | set_gender(from.gender()); 954 | } 955 | if (from.has_name()) { 956 | set_name(from.name()); 957 | } 958 | if (from.has_province()) { 959 | set_province(from.province()); 960 | } 961 | } 962 | mutable_unknown_fields()->MergeFrom(from.unknown_fields()); 963 | } 964 | 965 | void SetUserNameRequest::CopyFrom(const ::google::protobuf::Message& from) { 966 | if (&from == this) return; 967 | Clear(); 968 | MergeFrom(from); 969 | } 970 | 971 | void SetUserNameRequest::CopyFrom(const SetUserNameRequest& from) { 972 | if (&from == this) return; 973 | Clear(); 974 | MergeFrom(from); 975 | } 976 | 977 | bool SetUserNameRequest::IsInitialized() const { 978 | if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; 979 | 980 | return true; 981 | } 982 | 983 | void SetUserNameRequest::Swap(SetUserNameRequest* other) { 984 | if (other != this) { 985 | std::swap(gender_, other->gender_); 986 | std::swap(name_, other->name_); 987 | std::swap(province_, other->province_); 988 | std::swap(_has_bits_[0], other->_has_bits_[0]); 989 | _unknown_fields_.Swap(&other->_unknown_fields_); 990 | std::swap(_cached_size_, other->_cached_size_); 991 | } 992 | } 993 | 994 | ::google::protobuf::Metadata SetUserNameRequest::GetMetadata() const { 995 | protobuf_AssignDescriptorsOnce(); 996 | ::google::protobuf::Metadata metadata; 997 | metadata.descriptor = SetUserNameRequest_descriptor_; 998 | metadata.reflection = SetUserNameRequest_reflection_; 999 | return metadata; 1000 | } 1001 | 1002 | 1003 | // @@protoc_insertion_point(namespace_scope) 1004 | 1005 | } // namespace netserver 1006 | 1007 | // @@protoc_insertion_point(global_scope) 1008 | -------------------------------------------------------------------------------- /common/src/socket_connect.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Socket_Connect.cpp 3 | * 4 | * Created on: 2016-2-2 5 | * Author: wangfeng 6 | */ 7 | 8 | #include "socket_connect.h" 9 | 10 | Socket_Connect::Socket_Connect() 11 | { 12 | _sock_listen = NULL; 13 | msg_input = new Message_Process(); 14 | msg_input->setSockConnect(this); 15 | seqence++; 16 | } 17 | 18 | Socket_Connect::~Socket_Connect() 19 | { 20 | delete msg_input; 21 | } 22 | 23 | int Socket_Connect::OnRecv() 24 | { 25 | int ret = msg_input->recv(); 26 | if(ret == 0) // 对方关闭了连接 27 | { 28 | API_LOG_DEBUG(LM_DEBUG,"ip:%s close conection", _ip.c_str()); 29 | delete this; 30 | } 31 | else if(ret < 0) // 出错 32 | { 33 | API_LOG_DEBUG(LM_DEBUG,"ip:%s recv error", _ip.c_str()); 34 | delete this; 35 | } 36 | else 37 | { 38 | //do nothing 39 | } 40 | return 0; 41 | } 42 | 43 | int Socket_Connect::OnSend() 44 | { 45 | int ret = msg_input->send(); 46 | if(ret == 0) // 对方关闭了连接 47 | { 48 | API_LOG_DEBUG(LM_DEBUG,"ip:%s close conection", _ip.c_str()); 49 | delete this; 50 | } 51 | else if(ret < 0) // 出错 52 | { 53 | API_LOG_DEBUG(LM_DEBUG,"ip:%s recv error", _ip.c_str()); 54 | delete this; 55 | } 56 | else 57 | { 58 | API_LOG_DEBUG(LM_DEBUG,"Socket_Connect, success send %d len data", ret); 59 | this->SetEvent(FD_RECV|FD_CLOSE|FD_ERROR); //发送完成后去掉send的事件监听 60 | } 61 | return 0; 62 | } 63 | 64 | int Socket_Connect::OnClose() 65 | { 66 | return 0; 67 | } 68 | 69 | int Socket_Connect::OnError() 70 | { 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /common/src/socket_listen.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * socket_listen.cpp 3 | * 4 | * Created on: 2016-2-2 5 | * Author: wangfeng 6 | */ 7 | 8 | #include "socket_listen.h" 9 | 10 | Socket_Listen::Socket_Listen() 11 | { 12 | 13 | } 14 | 15 | Socket_Listen::~Socket_Listen() 16 | { 17 | 18 | } 19 | 20 | int Socket_Listen::Create(const char* bind_ip,short bind_port) 21 | { 22 | int listenfd = socket(AF_INET,SOCK_STREAM,0); 23 | int ret = 0; 24 | 25 | struct sockaddr_in server_addr; 26 | bzero(&server_addr,sizeof(server_addr)); 27 | server_addr.sin_family = AF_INET; 28 | server_addr.sin_port = htons(SERVER_PORT); 29 | server_addr.sin_addr.s_addr = htonl(INADDR_ANY); 30 | 31 | int flag = 1; 32 | ret = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); 33 | if(ret) 34 | { 35 | close(listenfd); 36 | API_LOG_DEBUG(LM_ERROR,"setsockopt failed, ret:%d, errno:%d", ret, errno); 37 | return -1; 38 | } 39 | 40 | ret = bind(listenfd,(struct sockaddr *)&server_addr,sizeof(server_addr)); 41 | if(ret) 42 | { 43 | close(listenfd); 44 | API_LOG_DEBUG(LM_ERROR,"bind error: %s",strerror(errno)); 45 | return -1; 46 | } 47 | 48 | flag = fcntl(listenfd, F_GETFL); 49 | if ( fcntl(listenfd, F_SETFL, O_NONBLOCK | flag) < 0 ) 50 | { 51 | close(listenfd); 52 | API_LOG_DEBUG(LM_ERROR,"HandleConnect set noblock socket:%d error:%s", listenfd,strerror(errno)); 53 | return -1; 54 | } 55 | 56 | if(listen(listenfd, 1024)<0) 57 | { 58 | close(listenfd); 59 | API_LOG_DEBUG(LM_ERROR,"CreateListen listen fd:%d err:%s", listenfd,strerror(errno)); 60 | return -1; 61 | } 62 | _sock_fd = listenfd; 63 | return 0; 64 | } 65 | 66 | int Socket_Listen::OnRecv() 67 | { 68 | API_LOG_DEBUG(LM_DEBUG,"enter into CSockListen OnRecv\n"); 69 | int length = sizeof(struct sockaddr_in); 70 | 71 | /* 72 | * 此种方式处理连接请求,listen要用LT模式,不要用ET模式,否则accept到的连接可能少于请求的连接 73 | */ 74 | int connfd = accept(_sock_fd,(struct sockaddr *)&client_addr,(socklen_t*)&length); 75 | if ( connfd <= 0 ) 76 | { 77 | // 多进程情况下,会争着accept,所以导致有些报错 78 | if (connfd != -1) 79 | { 80 | API_LOG_DEBUG(LM_ERROR,"netlisten accept rtn:%d error:%s\n", connfd, strerror(errno)); 81 | } 82 | return -1; 83 | } 84 | 85 | int flag = fcntl (connfd, F_GETFL); 86 | if ( fcntl (connfd, F_SETFL, O_NONBLOCK | flag) < 0 ) 87 | { 88 | API_LOG_DEBUG(LM_ERROR,"HandleConnect set noblock socket:%d error:%s\n", connfd,strerror(errno)); 89 | close(connfd); 90 | return -1; 91 | } 92 | 93 | if (AllocConnfd(connfd) < 0 ) 94 | { 95 | API_LOG_DEBUG(LM_ERROR,"CSockListen alloc proxy connfd error\n"); 96 | close(connfd); 97 | return -1; 98 | } 99 | 100 | /* 101 | * 若listenfd为ET模式,则要如此处理请求 102 | 103 | while((connfd = accept(_sock_fd,(struct sockaddr *)&client_addr,(socklen_t*)&length)) > 0) 104 | { 105 | int flag = fcntl (connfd, F_GETFL); 106 | if ( fcntl (connfd, F_SETFL, O_NONBLOCK | flag) < 0 ) 107 | { 108 | API_LOG_DEBUG(LM_ERROR,"HandleConnect set noblock socket:%d error:%s\n", connfd,strerror(errno)); 109 | close(connfd); 110 | return -1; 111 | } 112 | 113 | if (AllocConnfd(connfd) < 0 ) 114 | { 115 | API_LOG_DEBUG(LM_ERROR,"CSockListen alloc proxy connfd error\n"); 116 | close(connfd); 117 | return -1; 118 | } 119 | } 120 | */ 121 | 122 | return 0; 123 | } 124 | 125 | int Socket_Listen::OnSend() 126 | { 127 | return 0; 128 | } 129 | 130 | int Socket_Listen::OnClose() 131 | { 132 | return 0; 133 | } 134 | 135 | int Socket_Listen::OnError() 136 | { 137 | return 0; 138 | } 139 | 140 | int Socket_Listen::AllocConnfd(int connfd) 141 | { 142 | Socket_Connect * socket_connect = new Socket_Connect(); 143 | if (!socket_connect ) 144 | { 145 | API_LOG_DEBUG(LM_ERROR,"CSockListen alloc CSockClient error:%s",strerror(errno)); 146 | return -1; 147 | } 148 | static int sequence = 0; 149 | unsigned clientip = client_addr.sin_addr.s_addr; 150 | char* ip_str; 151 | struct in_addr _in; 152 | _in.s_addr = clientip; 153 | ip_str = inet_ntoa(_in); 154 | API_LOG_DEBUG(LM_DEBUG,"alloc connfd:%d, ip is %s",connfd, ip_str); 155 | socket_connect->setClientIP(ip_str); 156 | socket_connect->_sock_fd = connfd; 157 | socket_connect->AttachEpoller(_epoller); 158 | socket_connect->SetEvent(FD_RECV|FD_CLOSE|FD_ERROR); 159 | socket_connect->SetSockListen(this); 160 | socket_connect->setSqeuence(++sequence); 161 | return 0; 162 | } 163 | -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | ############################################################# 2 | # Makefile for executable file. 3 | # 编译静态链接库,每个cpp编写为一个可执行程序 4 | ############################################################# 5 | #set your own environment option 6 | 7 | cc = g++ 8 | flags = -W -g -Wno-deprecated 9 | INC=-I./common/include\ 10 | -I/usr/local/protobuf2.4.1/include\ 11 | -I/usr/local/sofa-pbrpc/include \ 12 | 13 | LIBS=-L./common/lib -lcommon\ 14 | -L/usr/local/sofa-pbrpc/lib -lsofa-pbrpc \ 15 | -L/usr/local/protobuf2.4.1/lib -lprotobuf -lprotoc -lprotobuf-lite\ 16 | -ldl -lpthread -lz 17 | 18 | TARGET=$(patsubst %.cpp,%,$(wildcard *.cpp)) 19 | 20 | .PHONY:all clean 21 | all:$(TARGET) 22 | 23 | %:%.cpp 24 | @echo "正在编译:" $<"---->"$@ 25 | $(cc) -o $@ $(flags) $< $(LIBS) $(INC) 26 | 27 | clean: 28 | rm -f obj/*.o $(TARGET) 29 | -------------------------------------------------------------------------------- /net_client.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * net_client.cpp 3 | * 4 | * Created on: 2016年1月28日 5 | * Author: fenngwang 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include "NetDefine.h" 19 | #include "log.h" 20 | #include "netserver.pb.h" 21 | 22 | using namespace std; 23 | using namespace CGI_LOG; 24 | 25 | #define SERVER_PORT 9999 26 | #define SERVER_IP "127.0.0.1" 27 | 28 | int process_buffer(char *buffer, uint32_t &already_recv_len); 29 | 30 | int main() 31 | { 32 | CGI_Log_Init(__FILE__); 33 | int sockfd = socket(AF_INET,SOCK_STREAM,0); 34 | 35 | struct sockaddr_in server_addr; 36 | bzero(&server_addr,sizeof(server_addr)); 37 | server_addr.sin_family = AF_INET; 38 | server_addr.sin_port = htons(SERVER_PORT); 39 | server_addr.sin_addr.s_addr = inet_addr(SERVER_IP); 40 | 41 | int ret = connect(sockfd,(const struct sockaddr *)&server_addr,sizeof(server_addr)); 42 | if(ret) 43 | { 44 | API_LOG_DEBUG(LM_ERROR, "connect failed, ret:%d, errno:%d", ret, errno); 45 | exit(1); 46 | } 47 | 48 | // 序列化数据 49 | char buffer[MaxPacketLength] = {0}; 50 | NetPacket obj_1; 51 | obj_1.netPacketHead.version = 1; 52 | obj_1.netPacketHead.cmd = CMD_GetUserName; 53 | obj_1.netPacketHead.serialNo = 1001; 54 | obj_1.netPacketHead.result = 0; 55 | netserver::GetUserNameRequest request; 56 | request.set_userid(1000); 57 | string strRequest_1; 58 | if(!request.SerializeToString(&strRequest_1)) 59 | { 60 | API_LOG_DEBUG(LM_ERROR, "SerializeToString"); 61 | exit(-1); 62 | } 63 | obj_1.netPacketHead.uiPacketLen = strRequest_1.length(); 64 | obj_1.Encode(); 65 | 66 | NetPacket obj_2; 67 | obj_2.netPacketHead.version = 2; 68 | obj_2.netPacketHead.cmd = CMD_GetUserName; 69 | obj_2.netPacketHead.serialNo = 1002; 70 | obj_2.netPacketHead.result = 1; 71 | request.set_userid(1003); 72 | string strRequest_2; 73 | if(!request.SerializeToString(&strRequest_2)) 74 | { 75 | API_LOG_DEBUG(LM_ERROR, "SerializeToString"); 76 | exit(-1); 77 | } 78 | obj_2.netPacketHead.uiPacketLen = strRequest_2.length(); 79 | obj_2.Encode(); 80 | 81 | NetPacket obj_3; 82 | obj_3.netPacketHead.version = 3; 83 | obj_3.netPacketHead.cmd = CMD_SetUserName; 84 | obj_3.netPacketHead.serialNo = 1003; 85 | obj_3.netPacketHead.result = 0; 86 | 87 | netserver::SetUserNameRequest setUserName; 88 | setUserName.set_gender(1); 89 | setUserName.set_name("fenngwang"); 90 | setUserName.set_province("广东"); 91 | string strUserName; 92 | if(!setUserName.SerializeToString(&strUserName)) 93 | { 94 | API_LOG_DEBUG(LM_ERROR, "SerializeToString"); 95 | exit(-1); 96 | } 97 | obj_3.netPacketHead.uiPacketLen = strUserName.length(); 98 | obj_3.Encode(); 99 | 100 | #if 1 101 | // 一个包,同一个包的头和包体分开发 102 | send(sockfd,&(obj_1.netPacketHead),PacketHeadLength,0); 103 | sleep(1); 104 | send(sockfd,strRequest_1.c_str(),strRequest_1.length(),0); 105 | sleep(1); 106 | #endif 107 | 108 | #if 1 109 | // 一个包,同一个包的头和包一起发 110 | memcpy(buffer, &(obj_1.netPacketHead), PacketHeadLength); 111 | memcpy(buffer+PacketHeadLength, strRequest_1.c_str(),strRequest_1.length()); 112 | send(sockfd,buffer,PacketHeadLength+strRequest_1.length(),0); 113 | sleep(1); 114 | #endif 115 | 116 | #if 1 117 | // 两个包一起发 118 | memcpy(buffer, &(obj_1.netPacketHead), PacketHeadLength); 119 | memcpy(buffer+PacketHeadLength, strRequest_1.c_str(),strRequest_1.length()); 120 | memcpy(buffer+PacketHeadLength+strRequest_1.length(), &(obj_2.netPacketHead), PacketHeadLength); 121 | memcpy(buffer+2*PacketHeadLength+strRequest_1.length(), strRequest_2.c_str(), strRequest_2.length()); 122 | send(sockfd,buffer,2*PacketHeadLength+strRequest_1.length()+strRequest_2.length(),0); 123 | sleep(1); 124 | #endif 125 | 126 | #if 1 127 | // 两个包分开发,一个包+第二个的包头,然后第二个的包体 128 | memcpy(buffer, &(obj_1.netPacketHead), PacketHeadLength); 129 | memcpy(buffer+PacketHeadLength, strRequest_1.c_str(),strRequest_1.length()); 130 | memcpy(buffer+PacketHeadLength+strRequest_1.length(), &(obj_2.netPacketHead), PacketHeadLength); 131 | send(sockfd,buffer,2*PacketHeadLength+strRequest_1.length(),0); 132 | sleep(1); 133 | memcpy(buffer, strRequest_2.c_str(), strRequest_2.length()); 134 | send(sockfd,buffer,strRequest_2.length(),0); 135 | sleep(1); 136 | #endif 137 | 138 | #if 1 139 | // 两个包分开发,一个包+第二个的包头-1,然后第二个的包头最后1+包体 140 | memcpy(buffer, &(obj_1.netPacketHead), PacketHeadLength); 141 | memcpy(buffer+PacketHeadLength, strRequest_1.c_str(),strRequest_1.length()); 142 | memcpy(buffer+PacketHeadLength+strRequest_1.length(), &(obj_2.netPacketHead), PacketHeadLength-1); 143 | send(sockfd,buffer,2*PacketHeadLength+strRequest_1.length()-1,0); 144 | sleep(1); 145 | memcpy(buffer, (char *)&(obj_2.netPacketHead)+PacketHeadLength-1, 1); 146 | memcpy(buffer+1, strRequest_2.c_str(), strRequest_2.length()); 147 | send(sockfd,buffer,1+strRequest_2.length(),0); 148 | sleep(1); 149 | #endif 150 | 151 | // 再发另外一个命令的包 152 | memcpy(buffer, &(obj_3.netPacketHead), PacketHeadLength); 153 | memcpy(buffer+PacketHeadLength, strUserName.c_str(),strUserName.length()); 154 | send(sockfd,buffer,PacketHeadLength+strUserName.length(),0); 155 | 156 | char recv_buffer[MaxPacketLength]; 157 | uint32_t recv_buffer_index = 0; 158 | while(1) 159 | { 160 | int ret = ::recv(sockfd,recv_buffer+recv_buffer_index,MaxPacketLength-recv_buffer_index,0); 161 | if(ret < 0) 162 | { 163 | if(errno == EWOULDBLOCK || errno == EAGAIN) // 没有数据了 164 | { 165 | return 1; 166 | } 167 | else if(errno == EINTR) 168 | { 169 | continue; 170 | } 171 | else 172 | { 173 | API_LOG_DEBUG(LM_ERROR,"recv error. ret:%d, errno:%d", ret, errno); 174 | return -1; 175 | } 176 | } 177 | else if(ret == 0) // 对方已经断掉 178 | { 179 | API_LOG_DEBUG(LM_ERROR,"recv close"); 180 | return 0; 181 | } 182 | else 183 | { 184 | recv_buffer_index += ret; 185 | API_LOG_DEBUG(LM_TRACE,"before process_buffer, recv_buffer_index:%d, ret:%d", recv_buffer_index, ret); 186 | if(process_buffer(recv_buffer, recv_buffer_index) < 0) 187 | { 188 | API_LOG_DEBUG(LM_ERROR,"process_buffer failed"); 189 | return -1; 190 | } 191 | API_LOG_DEBUG(LM_TRACE,"after process_buffer, recv_buffer_index:%d", recv_buffer_index); 192 | } 193 | } 194 | 195 | return 0; 196 | } 197 | 198 | int process_buffer(char *buffer, uint32_t &already_recv_len) 199 | { 200 | uint32_t unprocess_buffer_length = already_recv_len; // 未处理的缓冲区长度 201 | int start = 0; // 初始的读buffer的起点 202 | 203 | while(1) 204 | { 205 | API_LOG_DEBUG(LM_TRACE, "unprocess_buffer_length:%d, PacketHeadLength:%d", unprocess_buffer_length, PacketHeadLength); 206 | char *start_buffer = buffer+start; 207 | if(unprocess_buffer_length >= PacketHeadLength) // 长度比包头长 208 | { 209 | PacketHead header; 210 | transferBufferToPacketHead(start_buffer, header); 211 | if(header.uiPacketLen > MaxPacketLength-PacketHeadLength) // 客户端的包,包体太长 212 | { 213 | API_LOG_DEBUG(LM_TRACE, "header.uiPacketLen:%d > MaxPacketContentLength:%d", header.uiPacketLen, MaxPacketLength-PacketHeadLength); 214 | return -1; 215 | } 216 | 217 | if(unprocess_buffer_length < PacketHeadLength+header.uiPacketLen) // 没有接收完 218 | { 219 | API_LOG_DEBUG(LM_TRACE, "length:%d < PacketHeadLength+header.uiPacketLen:%d", unprocess_buffer_length, PacketHeadLength+header.uiPacketLen); 220 | if(start > 0) // buffer中有完整的包,已经处理过,则要移动buffer 221 | { 222 | memmove(buffer, buffer+start, unprocess_buffer_length); 223 | } 224 | return 0; 225 | } 226 | else if(unprocess_buffer_length >= PacketHeadLength+header.uiPacketLen) // 已经有了一个完整的包 227 | { 228 | switch(header.cmd) 229 | { 230 | case CMD_GetUserName: 231 | { 232 | /* 233 | * 接收数据 234 | */ 235 | API_LOG_DEBUG(LM_TRACE,"recv a packet, cmd:%d", header.cmd); 236 | netserver::GetUserNameResponse request; 237 | if(!request.ParseFromArray(start_buffer+PacketHeadLength,header.uiPacketLen)) 238 | { 239 | API_LOG_DEBUG(LM_ERROR, "ParseFromArray, cmd:%d", header.cmd); 240 | return -1; 241 | } 242 | API_LOG_DEBUG(LM_TRACE,"success, name is %s, province is %s",request.name().c_str(), request.province().c_str()); 243 | start+=PacketHeadLength+header.uiPacketLen; // 更新起始位置 244 | unprocess_buffer_length = unprocess_buffer_length - PacketHeadLength-header.uiPacketLen; // 剩余的未读缓冲区长度 245 | already_recv_len = unprocess_buffer_length; 246 | break; 247 | } 248 | case CMD_SetUserName: 249 | { 250 | /* 251 | * 接收数据 252 | */ 253 | API_LOG_DEBUG(LM_TRACE," success, recv a packet, cmd:%d, result:%d", header.cmd), header.result; 254 | start+=PacketHeadLength+header.uiPacketLen; // 更新起始位置 255 | unprocess_buffer_length = unprocess_buffer_length - PacketHeadLength-header.uiPacketLen; // 剩余的未读缓冲区长度 256 | already_recv_len = unprocess_buffer_length; 257 | break; 258 | } 259 | default: 260 | API_LOG_DEBUG(LM_ERROR,"success, recv a undefined packet, cmd:%d", header.cmd); 261 | start+=PacketHeadLength+header.uiPacketLen; // 更新起始位置 262 | unprocess_buffer_length = unprocess_buffer_length - PacketHeadLength-header.uiPacketLen; // 剩余的未读缓冲区长度 263 | already_recv_len = unprocess_buffer_length; 264 | break; 265 | } 266 | } 267 | } 268 | else // 包头都不够 269 | { 270 | API_LOG_DEBUG(LM_TRACE, "unprocess_buffer_length:%d < PacketHeadLength:%d", unprocess_buffer_length,PacketHeadLength); 271 | if(start > 0) // buffer中有完整的包,已经处理过,则要移动buffer 272 | { 273 | memmove(buffer, buffer+start, unprocess_buffer_length); 274 | } 275 | return 0; 276 | } 277 | } 278 | return 0; 279 | } 280 | -------------------------------------------------------------------------------- /net_server.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * net_server.cpp 3 | * 4 | * Created on: 2016年1月28日 5 | * Author: fenngwang 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include "log.h" 18 | #include "socket_listen.h" 19 | #include "epoller.h" 20 | 21 | using namespace std; 22 | using namespace CGI_LOG; 23 | 24 | #define SERVER_PORT 9999 25 | 26 | int main() 27 | { 28 | CGI_Log_Init(__FILE__); 29 | 30 | Socket_Listen socket_listen; 31 | int ret = socket_listen.Create("127.0.0.1",SERVER_PORT); 32 | if(ret) 33 | { 34 | API_LOG_DEBUG(LM_ERROR, "create listen sockfd failed."); 35 | exit(-1); 36 | } 37 | 38 | CEPoller _epoller; 39 | _epoller.Create(65536); 40 | socket_listen.AttachEpoller(&_epoller); 41 | socket_listen.SetEvent(FD_RECV|FD_CLOSE|FD_ERROR); 42 | 43 | //启动循环 44 | _epoller.LoopForEvent(10); 45 | 46 | return 0; 47 | } 48 | 49 | 50 | 51 | --------------------------------------------------------------------------------