1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
| #include "TCPServer.hpp" #include "TransProtocol.h"
#define MAGIC "SYL " #define DEFAULT_QUEUE_NUM 5
TCPServer::TCPServer(std::string ipStr, unsigned int port) { if (true == ipStr.empty() || 0 >= ipStr.length()) { std::cout << "Ip 地址不能为空!" << std::endl; return; } serverSockfd = socket(PF_INET, SOCK_STREAM, 0); if (0 > serverSockfd) { std::cout << "创建 socket 失败!" << std::endl; return; } std::cout << "创建 socket 成功!" << std::endl; int opt = 1; setsockopt(serverSockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); serAddrLen = sizeof(serverAddr); memset(&serverAddr, 0, serAddrLen); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port); serverAddr.sin_addr.s_addr = inet_addr(ipStr.c_str()); maxFd = serverSockfd; FD_ZERO(&masterSet); FD_SET(serverSockfd, &masterSet); }
TCPServer::~TCPServer() { for (int sockfd = 0; sockfd <= maxFd; sockfd++) { if (FD_ISSET(sockfd, &masterSet)) { std::cout << "关闭(sockfd = " << sockfd << ") !" << std::endl; close(sockfd); } } }
RetValue TCPServer::BindAddr() { int ret = bind(serverSockfd, (struct sockaddr*)&serverAddr, serAddrLen); if (0 != ret) { std::cout << "绑定 IP 地址和端口失败!" << std::endl; return Ret_failed; } std::cout << "绑定 IP 地址和端口成功!" << std::endl; return Ret_success; }
RetValue TCPServer::Listen(unsigned int queueNum) { int ret = listen(serverSockfd, 0 >= queueNum ? DEFAULT_QUEUE_NUM : queueNum); if (0 != ret) { std::cout << "监听端口失败!" << std::endl; return Ret_failed; } std::cout << "监听端口成功!" << std::endl; return Ret_success; }
RetValue TCPServer::Run() { pthread_t threadId; int ret = pthread_create(&threadId, NULL, CheckHeartBeat, (void*)this); if (0 != ret) { std::cout << "创建 心跳检测 线程失败!" << std::endl; return Ret_failed; } while (1) { FD_ZERO(&workingSet); memcpy(&workingSet, &masterSet, sizeof(masterSet)); timeout.tv_sec = 30; timeout.tv_usec = 0; int nums = select(maxFd + 1, &workingSet, NULL, NULL, &timeout); if (0 > nums) { std::cout << "select 出错!" << std::endl; return Ret_error; } else if (0 == nums) { continue; } else { if (FD_ISSET(serverSockfd, &workingSet)) { AcceptConn(); } else { RecvMsg(); } } } return Ret_success; }
RetValue TCPServer::AcceptConn() { struct sockaddr_in clientAddr; socklen_t cliAddrLen = sizeof(clientAddr); std::cout << "等待客户端连接。。。" << std::endl; int clientSockfd = accept(serverSockfd, (struct sockaddr*)&clientAddr, &cliAddrLen); if (0 > clientSockfd) { std::cout << "服务器接受客户端连接失败!" << std::endl; return Ret_failed; } std::string ipStr = inet_ntoa(clientAddr.sin_addr); std::cout << "服务器接受客户端(sockfd = " << clientSockfd << " ,ip = " << ipStr << ")连接成功!" << std::endl; sockfdMap.insert(make_pair(clientSockfd, make_pair(ipStr, 0))); FD_SET(clientSockfd, &masterSet); if (clientSockfd > maxFd) { maxFd = clientSockfd; } return Ret_success; }
#pragma mark -- 格式化发送数据 int TCPServer::RespDataFormat(char *buf, unsigned int bufLen, unsigned int cmd, unsigned int status, const char userId[]) { if(NULL == buf) { return -1; } size_t uIdLen = (NULL == userId ? 0 : strlen(userId)); if(bufLen < (sizeof(MsgResp) + uIdLen)) { return -2; } MsgResp *msgResp = (MsgResp *)buf; memcpy(&msgResp->magic, MAGIC, 4); msgResp->cmd = htonl(cmd); msgResp->status = htonl(status); if(userId != NULL) { memcpy(msgResp->userId, userId, uIdLen); } return (int)(uIdLen + sizeof(MsgResp)); }
#pragma mark -- 数据解析 int TCPServer::ReqDataParse(char *buf, unsigned int msgLen, unsigned int *cmd, char *userId) { if(NULL == buf) { return -1; } if(msgLen < (sizeof(MsgReq))) { return -2; } MsgReq *msgReq = (MsgReq *)buf; if (0 != memcmp(MAGIC, &msgReq->magic, 4)) { return -3; } if(NULL != cmd) { *cmd = ntohl(msgReq->cmd); } if(NULL != userId && msgLen > sizeof(MsgReq)) { memcpy(userId, msgReq->userId, msgLen - sizeof(MsgReq)); } return 0; }
RetValue TCPServer::RecvMsg() { char recvBuf[BUFF_SIZE]; char sendBuf[BUFF_SIZE]; ssize_t recvLen = 0; ssize_t sendMsgLen = 0; for(int sockfd = 0; sockfd <= maxFd; sockfd++) { if(FD_ISSET(sockfd, &workingSet)) { bool closeConn = false; memset(recvBuf, 0, BUFF_SIZE); memset(sendBuf, 0, BUFF_SIZE); recvLen = recv(sockfd, &recvBuf, BUFF_SIZE, 0); if (0 > recvLen) { std::cout << "接收消息出错(sockfd = " << sockfd << ")!" << std::endl; closeConn = true; } else if (0 == recvLen) { std::cout << "接收消息失败,(sockfd = " << sockfd << ")客户端连接已断开!" << std::endl; closeConn = true; } else { MsgHead *recvMsgH = (MsgHead*)recvBuf; if(Msg_heart == recvMsgH->msgType) { sockfdMap[sockfd].second = 0; std::cout << "接收客户端(sockfd = " << sockfd << ")的心跳数据:" << recvMsgH->data << std::endl; } else { unsigned int reqCmd = 0; unsigned int respCmd = 0; char userId[512]; memset(userId, 0, 512); MsgHead *sendMsgH = (MsgHead *)sendBuf; if (0 == ReqDataParse(recvMsgH->data, recvMsgH->msgLen, &reqCmd, userId)) { std::cout << "接收到客户端(sockfd = " << sockfd << ")请求:cmd:" << reqCmd << "\tuserId:" << userId << std::endl; sleep(3); respCmd = reqCmd + 1; switch ((CmdType)reqCmd) { case Cmd_reqStatus: { sendMsgLen = RespDataFormat(sendMsgH->data, BUFF_SIZE - sizeof(MsgHead), respCmd, Status_suspended, userId); } break; case Cmd_reqWakeUp: { sendMsgLen = RespDataFormat(sendMsgH->data, BUFF_SIZE - sizeof(MsgHead), respCmd, Status_waking, userId); } break; case Cmd_reqSuspend: { sendMsgLen = RespDataFormat(sendMsgH->data, BUFF_SIZE - sizeof(MsgHead), respCmd, Status_suspending, userId); } break; default: break; } sendMsgH->msgLen = (unsigned int)sendMsgLen; } else { std::cout << "接收客户端(sockfd = " << sockfd << ")的数据:" << recvMsgH->data << std::endl;
sendMsgLen = recvLen - sizeof(MsgHead); sendMsgH->msgLen = (unsigned int)sendMsgLen; memcpy(sendMsgH->data, recvMsgH->data, sendMsgLen); } sendMsgH->msgType = Msg_other; ssize_t sendLen = send(sockfd, sendBuf, sendMsgLen + sizeof(MsgHead), 0); if (0 > sendLen) { std::cout << "发送消息出错!" << std::endl; closeConn = true; } else if (0 == sendLen) { std::cout << "发送消息失败,连接已断开!" << std::endl; closeConn = true; } else { if (0 == strcmp(recvMsgH->data, "quit")) { std::cout << "客户端(sockfd = " << sockfd << ")已主动关闭" << std::endl; closeConn = true; } } } } if(true == closeConn) { std::cout << "关闭客户端(sockfd = " << sockfd << ")" << std::endl; close(sockfd); FD_CLR(sockfd, &masterSet); sockfdMap.erase(sockfd); if(sockfd == maxFd) { while(false == FD_ISSET(maxFd, &masterSet)) { maxFd--; } } } } } return Ret_success; }
#pragma mark -- 心跳检测 线程 void* CheckHeartBeat(void* arg) { std::cout << "心跳检测 线程启动!" << std::endl; TCPServer* server = (TCPServer*)arg; while(1) { std::cout << "当前已连接客户端数量:" << server->sockfdMap.size() << std::endl; std::map<int, std::pair<std::string, int>>::iterator it = server->sockfdMap.begin(); for( ; it != server->sockfdMap.end(); ) { if(CHECK_HB_COUNT <= it->second.second) { int sockfd = it->first; std::string ipStr = it->second.first; std::cout << "客户端(sockfd = " << sockfd << "ipStr = " << ipStr << ")已经掉线" << std::endl;
close(sockfd); FD_CLR(sockfd, &server->masterSet); if(sockfd == server->maxFd) { while(false == FD_ISSET(server->maxFd, &server->masterSet)) { server->maxFd--; } } server->sockfdMap.erase(it++); } else if(CHECK_HB_COUNT > it->second.second && 0 <= it->second.second) { it->second.second += 1; it++; } else { it++; } } sleep(HB_INTERVAL); } }
|