开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 644

fate-intel/HP-Socket

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
dev
分支 (2)
标签 (16)
dev
master
v6.0.1
v5.9.5
v5.9.4
v5.9.3
v5.9.2
v5.9.1
v5.8.8
v5.8.7
v5.8.6
v5.8.5
v5.8.4
v5.8.3
v5.8.2
v5.8.1
v5.7.3
v5.7.2
dev
分支 (2)
标签 (16)
dev
master
v6.0.1
v5.9.5
v5.9.4
v5.9.3
v5.9.2
v5.9.1
v5.8.8
v5.8.7
v5.8.6
v5.8.5
v5.8.4
v5.8.3
v5.8.2
v5.8.1
v5.7.3
v5.7.2
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
dev
分支 (2)
标签 (16)
dev
master
v6.0.1
v5.9.5
v5.9.4
v5.9.3
v5.9.2
v5.9.1
v5.8.8
v5.8.7
v5.8.6
v5.8.5
v5.8.4
v5.8.3
v5.8.2
v5.8.1
v5.7.3
v5.7.2
HP-Socket
/
Linux
/
src
/
UdpServer.cpp
HP-Socket
/
Linux
/
src
/
UdpServer.cpp
UdpServer.cpp 26.76 KB
一键复制 编辑 原始数据 按行查看 历史
伤神小怪兽 提交于 2024年01月30日 22:19 +08:00 . 20240130
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 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
/*
* Copyright: JessMA Open Source (ldcsaa@gmail.com)
*
* Author : Bruce Liang
* Website : https://github.com/ldcsaa
* Project : https://github.com/ldcsaa/HP-Socket
* Blog : http://www.cnblogs.com/ldcsaa
* Wiki : http://www.oschina.net/p/hp-socket
* QQ Group : 44636872, 75375912
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "UdpServer.h"
#ifdef _UDP_SUPPORT
EnHandleResult CUdpServer::TriggerFireAccept(TUdpSocketObj* pSocketObj)
{
EnHandleResult rs = TRIGGER(FireAccept(pSocketObj));
return rs;
}
BOOL CUdpServer::Start(LPCTSTR lpszBindAddress, USHORT usPort)
{
if(!CheckParams() || !CheckStarting())
return FALSE;
PrepareStart();
if(CreateListenSocket(lpszBindAddress, usPort))
if(CreateWorkerThreads())
if(StartAccept())
{
m_enState = SS_STARTED;
return TRUE;
}
EXECUTE_RESTORE_ERROR(Stop());
return FALSE;
}
void CUdpServer::SetLastError(EnSocketError code, LPCSTR func, int ec)
{
m_enLastError = code;
::SetLastError(ec);
}
BOOL CUdpServer::CheckParams()
{
if ((m_enSendPolicy >= SP_PACK && m_enSendPolicy <= SP_DIRECT) &&
(m_enOnSendSyncPolicy >= OSSP_NONE && m_enOnSendSyncPolicy <= OSSP_RECEIVE) &&
((int)m_dwMaxConnectionCount > 0 && m_dwMaxConnectionCount <= MAX_CONNECTION_COUNT) &&
((int)m_dwWorkerThreadCount > 0 && m_dwWorkerThreadCount <= MAX_WORKER_THREAD_COUNT) &&
((int)m_dwFreeSocketObjLockTime >= 1000) &&
((int)m_dwFreeSocketObjPool >= 0) &&
((int)m_dwFreeBufferObjPool >= 0) &&
((int)m_dwFreeSocketObjHold >= 0) &&
((int)m_dwFreeBufferObjHold >= 0) &&
((int)m_dwMaxDatagramSize > 0 && m_dwMaxDatagramSize <= MAXIMUM_UDP_MAX_DATAGRAM_SIZE) &&
((int)m_dwPostReceiveCount > 0) &&
((int)m_dwDetectAttempts >= 0) &&
((int)m_dwDetectInterval >= 1000 || m_dwDetectInterval == 0) )
return TRUE;
SetLastError(SE_INVALID_PARAM, __FUNCTION__, ERROR_INVALID_PARAMETER);
return FALSE;
}
void CUdpServer::PrepareStart()
{
m_bfActiveSockets.Reset(m_dwMaxConnectionCount);
m_lsFreeSocket.Reset(m_dwFreeSocketObjPool);
m_bfObjPool.SetItemCapacity(m_dwMaxDatagramSize);
m_bfObjPool.SetPoolSize(m_dwFreeBufferObjPool);
m_bfObjPool.SetPoolHold(m_dwFreeBufferObjHold);
m_bfObjPool.Prepare();
m_quSends = make_unique<CSendQueue[]>(m_dwWorkerThreadCount);
m_rcBuffers = make_unique<CBufferPtr[]>(m_dwWorkerThreadCount);
for_each(m_rcBuffers.get(), m_rcBuffers.get() + m_dwWorkerThreadCount, [this](CBufferPtr& buff) {buff.Malloc(m_dwMaxDatagramSize);});
m_soListens = make_unique<SOCKET[]>(m_dwWorkerThreadCount);
for_each(m_soListens.get(), m_soListens.get() + m_dwWorkerThreadCount, [](SOCKET& sock) {sock = INVALID_FD;});
}
BOOL CUdpServer::CheckStarting()
{
CSpinLock locallock(m_csState);
if(m_enState == SS_STOPPED)
m_enState = SS_STARTING;
else
{
SetLastError(SE_ILLEGAL_STATE, __FUNCTION__, ERROR_INVALID_STATE);
return FALSE;
}
return TRUE;
}
BOOL CUdpServer::CheckStoping()
{
if(m_enState != SS_STOPPED)
{
CSpinLock locallock(m_csState);
if(HasStarted())
{
m_enState = SS_STOPPING;
return TRUE;
}
}
SetLastError(SE_ILLEGAL_STATE, __FUNCTION__, ERROR_INVALID_STATE);
return FALSE;
}
BOOL CUdpServer::CreateListenSocket(LPCTSTR lpszBindAddress, USHORT usPort)
{
if(::IsStrEmpty(lpszBindAddress))
lpszBindAddress = DEFAULT_IPV4_BIND_ADDRESS;
HP_SOCKADDR addr;
if(!::sockaddr_A_2_IN(lpszBindAddress, usPort, addr))
{
SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError());
return FALSE;
}
for(DWORD i = 0; i < m_dwWorkerThreadCount; i++)
{
m_soListens[i] = socket(addr.family, SOCK_DGRAM, IPPROTO_UDP);
SOCKET soListen = m_soListens[i];
if(IS_INVALID_FD(soListen))
{
SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError());
return FALSE;
}
::fcntl_SETFL(soListen, O_NOATIME | O_NONBLOCK | O_CLOEXEC);
VERIFY(IS_NO_ERROR(::SSO_ReuseAddress(soListen, m_enReusePolicy)));
if(IS_HAS_ERROR(::bind(soListen, addr.Addr(), addr.AddrSize())))
{
SetLastError(SE_SOCKET_BIND, __FUNCTION__, ::WSAGetLastError());
return FALSE;
}
if(TRIGGER(FirePrepareListen(soListen)) == HR_ERROR)
{
SetLastError(SE_SOCKET_PREPARE, __FUNCTION__, ENSURE_ERROR_CANCELLED);
return FALSE;
}
}
return TRUE;
}
BOOL CUdpServer::CreateWorkerThreads()
{
return m_ioDispatcher.Start(this, m_dwPostReceiveCount, m_dwWorkerThreadCount);
}
BOOL CUdpServer::StartAccept()
{
for(int i = 0; i < (int)m_dwWorkerThreadCount; i++)
{
SOCKET& soListen = m_soListens[i];
if(!m_ioDispatcher.AddFD(i, soListen, EPOLLIN | EPOLLOUT | EPOLLET, TO_PVOID(&soListen)))
return FALSE;
}
return TRUE;
}
BOOL CUdpServer::Stop()
{
if(!CheckStoping())
return FALSE;
SendCloseNotify();
CloseListenSocket();
DisconnectClientSocket();
WaitForClientSocketClose();
WaitForWorkerThreadEnd();
ReleaseClientSocket();
FireShutdown();
ReleaseFreeSocket();
ClearSendQueues();
Reset();
return TRUE;
}
void CUdpServer::SendCloseNotify()
{
if(!m_soListens)
return;
if(m_bfActiveSockets.Elements() == 0)
return;
TUdpSocketObjPtrPool::IndexSet indexes;
m_bfActiveSockets.CopyIndexes(indexes);
for(auto it = indexes.begin(), end = indexes.end(); it != end; ++it)
{
CONNID connID = *it;
TUdpSocketObj* pSocketObj = FindSocketObj(connID);
if(TUdpSocketObj::IsValid(pSocketObj))
::SendUdpCloseNotify(m_soListens[pSocketObj->index], pSocketObj->remoteAddr);
}
::WaitFor(30);
}
void CUdpServer::CloseListenSocket()
{
if(m_soListens)
{
for_each(m_soListens.get(), m_soListens.get() + m_dwWorkerThreadCount, [](SOCKET& sock)
{
if(sock != INVALID_FD)
{
::ManualCloseSocket(sock);
sock = INVALID_FD;
}
});
::WaitFor(70);
}
}
void CUdpServer::DisconnectClientSocket()
{
if(m_bfActiveSockets.Elements() == 0)
return;
TUdpSocketObjPtrPool::IndexSet indexes;
m_bfActiveSockets.CopyIndexes(indexes);
for(auto it = indexes.begin(), end = indexes.end(); it != end; ++it)
Disconnect(*it);
}
void CUdpServer::WaitForClientSocketClose()
{
while(m_bfActiveSockets.Elements() > 0)
::WaitFor(50);
}
void CUdpServer::WaitForWorkerThreadEnd()
{
m_ioDispatcher.Stop();
}
void CUdpServer::ReleaseClientSocket()
{
VERIFY(m_bfActiveSockets.IsEmpty());
m_bfActiveSockets.Reset();
CWriteLock locallock(m_csClientSocket);
m_mpClientAddr.clear();
}
void CUdpServer::ReleaseFreeSocket()
{
m_lsFreeSocket.Clear();
ReleaseGCSocketObj(TRUE);
VERIFY(m_lsGCSocket.IsEmpty());
}
void CUdpServer::ClearSendQueues()
{
if(m_quSends) for_each(m_quSends.get(), m_quSends.get() + m_dwWorkerThreadCount, [](CSendQueue& queue) {queue.UnsafeClear();});
}
void CUdpServer::Reset()
{
m_phSocket.Reset();
m_bfObjPool.Clear();
m_soListens = nullptr;
m_rcBuffers = nullptr;
m_quSends = nullptr;
m_enState = SS_STOPPED;
m_evWait.SyncNotifyAll();
}
TUdpSocketObj* CUdpServer::GetFreeSocketObj(CONNID dwConnID)
{
DWORD dwIndex;
TUdpSocketObj* pSocketObj = nullptr;
if(m_lsFreeSocket.TryLock(&pSocketObj, dwIndex))
{
if(::GetTimeGap32(pSocketObj->freeTime) >= m_dwFreeSocketObjLockTime)
VERIFY(m_lsFreeSocket.ReleaseLock(nullptr, dwIndex));
else
{
VERIFY(m_lsFreeSocket.ReleaseLock(pSocketObj, dwIndex));
pSocketObj = nullptr;
}
}
if(!pSocketObj) pSocketObj = CreateSocketObj();
pSocketObj->Reset(dwConnID);
return pSocketObj;
}
TUdpSocketObj* CUdpServer::CreateSocketObj()
{
return TUdpSocketObj::Construct(m_phSocket, m_bfObjPool);
}
void CUdpServer::DeleteSocketObj(TUdpSocketObj* pSocketObj)
{
TUdpSocketObj::Destruct(pSocketObj);
}
void CUdpServer::AddFreeSocketObj(TUdpSocketObj* pSocketObj, EnSocketCloseFlag enFlag, EnSocketOperation enOperation, int iErrorCode, BOOL bNotify)
{
if(!InvalidSocketObj(pSocketObj))
return;
CloseClientSocketObj(pSocketObj, enFlag, enOperation, iErrorCode, bNotify);
{
m_bfActiveSockets.Remove(pSocketObj->connID);
CWriteLock locallock(m_csClientSocket);
m_mpClientAddr.erase(&pSocketObj->remoteAddr);
}
m_ioDispatcher.DelTimer(pSocketObj->index, pSocketObj->fdTimer);
TUdpSocketObj::Release(pSocketObj);
ReleaseGCSocketObj();
if(!m_lsFreeSocket.TryPut(pSocketObj))
m_lsGCSocket.PushBack(pSocketObj);
}
void CUdpServer::ReleaseGCSocketObj(BOOL bForce)
{
::ReleaseGCObj(m_lsGCSocket, m_dwFreeSocketObjLockTime, bForce);
}
BOOL CUdpServer::InvalidSocketObj(TUdpSocketObj* pSocketObj)
{
return TUdpSocketObj::InvalidSocketObj(pSocketObj);
}
void CUdpServer::AddClientSocketObj(int idx, CONNID dwConnID, TUdpSocketObj* pSocketObj, const HP_SOCKADDR& remoteAddr)
{
ASSERT(FindSocketObj(dwConnID) == nullptr);
pSocketObj->index = idx;
pSocketObj->pHolder = this;
pSocketObj->connTime = ::TimeGetTime();
pSocketObj->activeTime = pSocketObj->connTime;
if(IsNeedDetectConnection())
pSocketObj->fdTimer = m_ioDispatcher.AddTimer(pSocketObj->index, m_dwDetectInterval, pSocketObj);
remoteAddr.Copy(pSocketObj->remoteAddr);
pSocketObj->SetConnected();
VERIFY(m_bfActiveSockets.ReleaseLock(dwConnID, pSocketObj));
CWriteLock locallock(m_csClientSocket);
m_mpClientAddr[&pSocketObj->remoteAddr] = dwConnID;
}
TUdpSocketObj* CUdpServer::FindSocketObj(CONNID dwConnID)
{
TUdpSocketObj* pSocketObj = nullptr;
if(m_bfActiveSockets.Get(dwConnID, &pSocketObj) != TUdpSocketObjPtrPool::GR_VALID)
pSocketObj = nullptr;
return pSocketObj;
}
CONNID CUdpServer::FindConnectionID(const HP_SOCKADDR* pAddr)
{
CONNID dwConnID = 0;
CReadLock locallock(m_csClientSocket);
TSockAddrMapCI it = m_mpClientAddr.find(pAddr);
if(it != m_mpClientAddr.end())
dwConnID = it->second;
return dwConnID;
}
void CUdpServer::CloseClientSocketObj(TUdpSocketObj* pSocketObj, EnSocketCloseFlag enFlag, EnSocketOperation enOperation, int iErrorCode, BOOL bNotify)
{
ASSERT(TUdpSocketObj::IsExist(pSocketObj));
SOCKET soListen = m_soListens[pSocketObj->index];
if(bNotify && soListen != INVALID_SOCKET)
::SendUdpCloseNotify(soListen, pSocketObj->remoteAddr);
if(enFlag == SCF_CLOSE)
FireClose(pSocketObj, SO_CLOSE, SE_OK);
else if(enFlag == SCF_ERROR)
FireClose(pSocketObj, enOperation, iErrorCode);
}
BOOL CUdpServer::GetListenAddress(TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort)
{
ASSERT(lpszAddress != nullptr && iAddressLen > 0);
if(!HasStarted())
{
::SetLastError(ERROR_INVALID_STATE);
return FALSE;
}
return ::GetSocketLocalAddress(m_soListens[0], lpszAddress, iAddressLen, usPort);
}
BOOL CUdpServer::GetLocalAddress(CONNID dwConnID, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort)
{
ASSERT(lpszAddress != nullptr && iAddressLen > 0);
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(!TUdpSocketObj::IsValid(pSocketObj))
{
::SetLastError(ERROR_OBJECT_NOT_FOUND);
return FALSE;
}
return ::GetSocketLocalAddress(m_soListens[pSocketObj->index], lpszAddress, iAddressLen, usPort);
}
BOOL CUdpServer::GetRemoteAddress(CONNID dwConnID, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort)
{
ASSERT(lpszAddress != nullptr && iAddressLen > 0);
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(!TUdpSocketObj::IsExist(pSocketObj))
{
::SetLastError(ERROR_OBJECT_NOT_FOUND);
return FALSE;
}
ADDRESS_FAMILY usFamily;
return ::sockaddr_IN_2_A(pSocketObj->remoteAddr, usFamily, lpszAddress, iAddressLen, usPort);
}
BOOL CUdpServer::SetConnectionExtra(CONNID dwConnID, PVOID pExtra)
{
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
return SetConnectionExtra(pSocketObj, pExtra);
}
BOOL CUdpServer::SetConnectionExtra(TUdpSocketObj* pSocketObj, PVOID pExtra)
{
if(!TUdpSocketObj::IsExist(pSocketObj))
::SetLastError(ERROR_OBJECT_NOT_FOUND);
else
{
pSocketObj->extra = pExtra;
return TRUE;
}
return FALSE;
}
BOOL CUdpServer::GetConnectionExtra(CONNID dwConnID, PVOID* ppExtra)
{
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
return GetConnectionExtra(pSocketObj, ppExtra);
}
BOOL CUdpServer::GetConnectionExtra(TUdpSocketObj* pSocketObj, PVOID* ppExtra)
{
ASSERT(ppExtra != nullptr);
if(!TUdpSocketObj::IsExist(pSocketObj))
::SetLastError(ERROR_OBJECT_NOT_FOUND);
else
{
*ppExtra = pSocketObj->extra;
return TRUE;
}
return FALSE;
}
BOOL CUdpServer::SetConnectionReserved(CONNID dwConnID, PVOID pReserved)
{
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
return SetConnectionReserved(pSocketObj, pReserved);
}
BOOL CUdpServer::SetConnectionReserved(TUdpSocketObj* pSocketObj, PVOID pReserved)
{
if(!TUdpSocketObj::IsExist(pSocketObj))
::SetLastError(ERROR_OBJECT_NOT_FOUND);
else
{
pSocketObj->reserved = pReserved;
return TRUE;
}
return FALSE;
}
BOOL CUdpServer::GetConnectionReserved(CONNID dwConnID, PVOID* ppReserved)
{
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
return GetConnectionReserved(pSocketObj, ppReserved);
}
BOOL CUdpServer::GetConnectionReserved(TUdpSocketObj* pSocketObj, PVOID* ppReserved)
{
ASSERT(ppReserved != nullptr);
if(!TUdpSocketObj::IsExist(pSocketObj))
::SetLastError(ERROR_OBJECT_NOT_FOUND);
else
{
*ppReserved = pSocketObj->reserved;
return TRUE;
}
return FALSE;
}
BOOL CUdpServer::SetConnectionReserved2(CONNID dwConnID, PVOID pReserved2)
{
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
return SetConnectionReserved2(pSocketObj, pReserved2);
}
BOOL CUdpServer::SetConnectionReserved2(TUdpSocketObj* pSocketObj, PVOID pReserved2)
{
if(!TUdpSocketObj::IsExist(pSocketObj))
::SetLastError(ERROR_OBJECT_NOT_FOUND);
else
{
pSocketObj->reserved2 = pReserved2;
return TRUE;
}
return FALSE;
}
BOOL CUdpServer::GetConnectionReserved2(CONNID dwConnID, PVOID* ppReserved2)
{
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
return GetConnectionReserved2(pSocketObj, ppReserved2);
}
BOOL CUdpServer::GetConnectionReserved2(TUdpSocketObj* pSocketObj, PVOID* ppReserved2)
{
ASSERT(ppReserved2 != nullptr);
if(!TUdpSocketObj::IsExist(pSocketObj))
::SetLastError(ERROR_OBJECT_NOT_FOUND);
else
{
*ppReserved2 = pSocketObj->reserved2;
return TRUE;
}
return FALSE;
}
BOOL CUdpServer::IsPauseReceive(CONNID dwConnID, BOOL& bPaused)
{
::SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
bPaused = FALSE;
return FALSE;
}
BOOL CUdpServer::IsConnected(CONNID dwConnID)
{
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(!TUdpSocketObj::IsValid(pSocketObj))
{
::SetLastError(ERROR_OBJECT_NOT_FOUND);
return FALSE;
}
return pSocketObj->HasConnected();
}
BOOL CUdpServer::GetPendingDataLength(CONNID dwConnID, int& iPending)
{
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(!TUdpSocketObj::IsValid(pSocketObj))
::SetLastError(ERROR_OBJECT_NOT_FOUND);
else
{
iPending = pSocketObj->Pending();
return TRUE;
}
return FALSE;
}
DWORD CUdpServer::GetConnectionCount()
{
return m_bfActiveSockets.Elements();
}
BOOL CUdpServer::GetAllConnectionIDs(CONNID pIDs[], DWORD& dwCount)
{
return m_bfActiveSockets.GetAllElementIndexes(pIDs, dwCount);
}
BOOL CUdpServer::GetConnectPeriod(CONNID dwConnID, DWORD& dwPeriod)
{
BOOL isOK = TRUE;
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(TUdpSocketObj::IsValid(pSocketObj))
dwPeriod = ::GetTimeGap32(pSocketObj->connTime);
else
{
::SetLastError(ERROR_OBJECT_NOT_FOUND);
isOK = FALSE;
}
return isOK;
}
BOOL CUdpServer::GetSilencePeriod(CONNID dwConnID, DWORD& dwPeriod)
{
if(!m_bMarkSilence)
return FALSE;
BOOL isOK = TRUE;
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(TUdpSocketObj::IsValid(pSocketObj))
dwPeriod = ::GetTimeGap32(pSocketObj->activeTime);
else
{
::SetLastError(ERROR_OBJECT_NOT_FOUND);
isOK = FALSE;
}
return isOK;
}
BOOL CUdpServer::Disconnect(CONNID dwConnID, BOOL bForce)
{
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(!TUdpSocketObj::IsValid(pSocketObj))
{
::SetLastError(ERROR_OBJECT_NOT_FOUND);
return FALSE;
}
return m_ioDispatcher.SendCommandByIndex(pSocketObj->index, DISP_CMD_DISCONNECT, dwConnID, bForce);
}
BOOL CUdpServer::DisconnectLongConnections(DWORD dwPeriod, BOOL bForce)
{
if(dwPeriod > MAX_CONNECTION_PERIOD)
return FALSE;
if(m_bfActiveSockets.Elements() == 0)
return TRUE;
DWORD now = ::TimeGetTime();
TUdpSocketObjPtrPool::IndexSet indexes;
m_bfActiveSockets.CopyIndexes(indexes);
for(auto it = indexes.begin(), end = indexes.end(); it != end; ++it)
{
CONNID connID = *it;
TUdpSocketObj* pSocketObj = FindSocketObj(connID);
if(TUdpSocketObj::IsValid(pSocketObj) && (int)(now - pSocketObj->connTime) >= (int)dwPeriod)
Disconnect(connID, bForce);
}
return TRUE;
}
BOOL CUdpServer::DisconnectSilenceConnections(DWORD dwPeriod, BOOL bForce)
{
if(!m_bMarkSilence)
return FALSE;
if(dwPeriod > MAX_CONNECTION_PERIOD)
return FALSE;
if(m_bfActiveSockets.Elements() == 0)
return TRUE;
DWORD now = ::TimeGetTime();
TUdpSocketObjPtrPool::IndexSet indexes;
m_bfActiveSockets.CopyIndexes(indexes);
for(auto it = indexes.begin(), end = indexes.end(); it != end; ++it)
{
CONNID connID = *it;
TUdpSocketObj* pSocketObj = FindSocketObj(connID);
if(TUdpSocketObj::IsValid(pSocketObj) && (int)(now - pSocketObj->activeTime) >= (int)dwPeriod)
Disconnect(connID, bForce);
}
return TRUE;
}
BOOL CUdpServer::PauseReceive(CONNID dwConnID, BOOL bPause)
{
::SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return FALSE;
}
BOOL CUdpServer::OnBeforeProcessIo(const TDispContext* pContext, PVOID pv, UINT events)
{
if(pv == &m_soListens[pContext->GetIndex()])
return TRUE;
if(!(events & _EPOLL_ALL_ERROR_EVENTS))
DetectConnection(pv);
return FALSE;
}
VOID CUdpServer::OnAfterProcessIo(const TDispContext* pContext, PVOID pv, UINT events, BOOL rs)
{
}
VOID CUdpServer::OnCommand(const TDispContext* pContext, TDispCommand* pCmd)
{
CONNID dwConnID = (CONNID)(pCmd->wParam);
switch(pCmd->type)
{
case DISP_CMD_SEND:
HandleCmdSend(dwConnID, (int)(pCmd->lParam));
break;
case DISP_CMD_DISCONNECT:
HandleCmdDisconnect(dwConnID, (BOOL)pCmd->lParam);
break;
case DISP_CMD_TIMEOUT:
HandleCmdTimeout(dwConnID);
break;
}
}
VOID CUdpServer::HandleCmdDisconnect(CONNID dwConnID, BOOL bForce)
{
AddFreeSocketObj(FindSocketObj(dwConnID), SCF_CLOSE);
}
VOID CUdpServer::HandleCmdTimeout(CONNID dwConnID)
{
AddFreeSocketObj(FindSocketObj(dwConnID), SCF_CLOSE, SO_UNKNOWN, 0, FALSE);
}
BOOL CUdpServer::OnReadyRead(const TDispContext* pContext, PVOID pv, UINT events)
{
return HandleReceive(pContext, RETRIVE_EVENT_FLAG_H(events));
}
BOOL CUdpServer::OnReadyWrite(const TDispContext* pContext, PVOID pv, UINT events)
{
return HandleSend(pContext, RETRIVE_EVENT_FLAG_H(events));
}
BOOL CUdpServer::OnHungUp(const TDispContext* pContext, PVOID pv, UINT events)
{
return HandleClose(nullptr, SO_CLOSE, 0);
}
BOOL CUdpServer::OnError(const TDispContext* pContext, PVOID pv, UINT events)
{
return HandleClose(nullptr, SO_CLOSE, -1);
}
VOID CUdpServer::OnDispatchThreadStart(THR_ID tid)
{
OnWorkerThreadStart(tid);
}
VOID CUdpServer::OnDispatchThreadEnd(THR_ID tid)
{
OnWorkerThreadEnd(tid);
}
BOOL CUdpServer::HandleClose(TUdpSocketObj* pSocketObj, EnSocketOperation enOperation, int iErrorCode)
{
if(!HasStarted())
return FALSE;
else if(pSocketObj == nullptr)
{
TRACE("HandleClose() -> OP: %d, EC: %d", enOperation, iErrorCode);
return TRUE;
}
if(iErrorCode == -1)
iErrorCode = ::SSO_GetError(m_soListens[pSocketObj->index]);
EnSocketCloseFlag enFlag = IS_NO_ERROR(iErrorCode) ? SCF_CLOSE : SCF_ERROR;
AddFreeSocketObj(pSocketObj, enFlag, enOperation, iErrorCode);
return FALSE;
}
BOOL CUdpServer::HandleReceive(const TDispContext* pContext, int flag)
{
int idx = pContext->GetIndex();
CBufferPtr& buffer = m_rcBuffers[idx];
int iBufferLen = (int)buffer.Size();
while(TRUE)
{
HP_SOCKADDR addr;
socklen_t dwAddrLen = (socklen_t)addr.AddrSize();
int rc = (int)recvfrom(m_soListens[idx], buffer.Ptr(), iBufferLen, MSG_TRUNC, addr.Addr(), &dwAddrLen);
if(rc >= 0)
{
CONNID dwConnID = FindConnectionID(&addr);
if(dwConnID == 0)
{
if(rc > iBufferLen)
continue;
if((dwConnID = HandleAccept(pContext, addr)) == 0)
continue;
}
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
ASSERT(pSocketObj->index == idx);
if(!TUdpSocketObj::IsValid(pSocketObj))
continue;
if(rc == 0)
{
HandleZeroBytes(pSocketObj);
continue;
}
if(rc > iBufferLen)
{
AddFreeSocketObj(pSocketObj, SCF_ERROR, SO_RECEIVE, ERROR_BAD_LENGTH);
continue;
}
if(::IsUdpCloseNotify(buffer.Ptr(), rc))
{
AddFreeSocketObj(pSocketObj, SCF_CLOSE, SO_CLOSE, SE_OK, FALSE);
continue;
}
if(TRIGGER(FireReceive(pSocketObj, buffer.Ptr(), rc)) == HR_ERROR)
{
TRACE("<S-CNNID: %zu> OnReceive() event return 'HR_ERROR', connection will be closed !", dwConnID);
AddFreeSocketObj(pSocketObj, SCF_ERROR, SO_RECEIVE, ENSURE_ERROR_CANCELLED);;
continue;
}
}
else if(rc == SOCKET_ERROR)
{
int code = ::WSAGetLastError();
if(code == ERROR_WOULDBLOCK)
break;
else if(!HandleClose(nullptr, SO_RECEIVE, code))
return FALSE;
}
else
{
ASSERT(FALSE);
}
}
return TRUE;
}
CONNID CUdpServer::HandleAccept(const TDispContext* pContext, HP_SOCKADDR& addr)
{
int idx = pContext->GetIndex();
CONNID dwConnID = 0;
TUdpSocketObj* pSocketObj = nullptr;
if(!m_bfActiveSockets.AcquireLock(dwConnID))
{
::SendUdpCloseNotify(m_soListens[idx], addr);
return 0;
}
pSocketObj = GetFreeSocketObj(dwConnID);
AddClientSocketObj(idx, dwConnID, pSocketObj, addr);
if(TriggerFireAccept(pSocketObj) == HR_ERROR)
{
AddFreeSocketObj(pSocketObj);
dwConnID = 0;
}
return dwConnID;
}
void CUdpServer::HandleZeroBytes(TUdpSocketObj* pSocketObj)
{
TRACE("<S-CNNID: %zu> recv 0 bytes (detect package)", pSocketObj->connID);
pSocketObj->detectFails = 0;
#if defined(DEBUG_TRACE)
int rc = (int)
#endif
sendto(m_soListens[pSocketObj->index], nullptr, 0, 0, pSocketObj->remoteAddr.Addr(), pSocketObj->remoteAddr.AddrSize());
TRACE("<S-CNNID: %zu> send 0 bytes (detect ack package - %s)", pSocketObj->connID, IS_HAS_ERROR(rc) ? "fail" : "succ");
}
BOOL CUdpServer::HandleSend(const TDispContext* pContext, int flag)
{
CSendQueue& quSend = m_quSends[pContext->GetIndex()];
CONNID dwConnID = 0;
while(quSend.PopFront(&dwConnID))
HandleCmdSend(dwConnID, flag);
return TRUE;
}
VOID CUdpServer::HandleCmdSend(CONNID dwConnID, int flag)
{
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(!TUdpSocketObj::IsValid(pSocketObj) || !pSocketObj->IsPending())
return;
BOOL bBlocked = FALSE;
int writes = flag ? -1 : MAX_CONTINUE_WRITES;
TBufferObjList& sndBuff = pSocketObj->sndBuff;
TItemPtr itPtr(sndBuff);
for(int i = 0; i < writes || writes < 0; i++)
{
{
CReentrantCriSecLock locallock(pSocketObj->csSend);
itPtr = sndBuff.PopFront();
}
if(!itPtr.IsValid())
break;
ASSERT(!itPtr->IsEmpty());
if(!SendItem(pSocketObj, itPtr, bBlocked))
return;
if(bBlocked)
{
{
CReentrantCriSecLock locallock(pSocketObj->csSend);
sndBuff.PushFront(itPtr.Detach());
}
m_quSends[pSocketObj->index].PushBack(dwConnID);
break;
}
}
if(!bBlocked && pSocketObj->IsPending())
VERIFY(m_ioDispatcher.SendCommandByIndex(pSocketObj->index, DISP_CMD_SEND, dwConnID));
}
BOOL CUdpServer::SendItem(TUdpSocketObj* pSocketObj, TItem* pItem, BOOL& bBlocked)
{
int rc = (int)sendto(m_soListens[pSocketObj->index], pItem->Ptr(), pItem->Size(), 0, pSocketObj->remoteAddr.Addr(), pSocketObj->remoteAddr.AddrSize());
if(rc > 0)
{
ASSERT(rc == pItem->Size());
if(TRIGGER(FireSend(pSocketObj, pItem->Ptr(), rc)) == HR_ERROR)
{
TRACE("<S-CNNID: %zu> OnSend() event should not return 'HR_ERROR' !!", pSocketObj->connID);
ASSERT(FALSE);
}
}
else if(rc == SOCKET_ERROR)
{
int code = ::WSAGetLastError();
if(code == ERROR_WOULDBLOCK)
bBlocked = TRUE;
else if(!HandleClose(pSocketObj, SO_SEND, code))
return FALSE;
}
else
ASSERT(FALSE);
return TRUE;
}
BOOL CUdpServer::Send(CONNID dwConnID, const BYTE* pBuffer, int iLength, int iOffset)
{
ASSERT(pBuffer && iLength > 0 && iLength <= (int)m_dwMaxDatagramSize);
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
return DoSend(pSocketObj, pBuffer, iLength, iOffset);
}
BOOL CUdpServer::DoSend(TUdpSocketObj* pSocketObj, const BYTE* pBuffer, int iLength, int iOffset)
{
int result = NO_ERROR;
if(TUdpSocketObj::IsValid(pSocketObj))
{
if(pBuffer && iLength > 0 && iLength <= (int)m_dwMaxDatagramSize)
{
if(iOffset != 0) pBuffer += iOffset;
TItemPtr itPtr(m_bfObjPool, m_bfObjPool.PickFreeItem());
itPtr->Cat(pBuffer, iLength);
result = SendInternal(pSocketObj, itPtr);
}
else
result = ERROR_INVALID_PARAMETER;
}
else
result = ERROR_OBJECT_NOT_FOUND;
if(result != NO_ERROR)
::SetLastError(result);
return (result == NO_ERROR);
}
BOOL CUdpServer::SendPackets(CONNID dwConnID, const WSABUF pBuffers[], int iCount)
{
ASSERT(pBuffers && iCount > 0);
if(!pBuffers || iCount <= 0)
return ERROR_INVALID_PARAMETER;
TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(!TUdpSocketObj::IsValid(pSocketObj))
{
::SetLastError(ERROR_OBJECT_NOT_FOUND);
return FALSE;
}
int result = NO_ERROR;
int iLength = 0;
int iMaxLen = (int)m_dwMaxDatagramSize;
TItemPtr itPtr(m_bfObjPool, m_bfObjPool.PickFreeItem());
for(int i = 0; i < iCount; i++)
{
int iBufLen = pBuffers[i].len;
if(iBufLen > 0)
{
BYTE* pBuffer = (BYTE*)pBuffers[i].buf;
ASSERT(pBuffer);
iLength += iBufLen;
if(iLength <= iMaxLen)
itPtr->Cat(pBuffer, iBufLen);
else
break;
}
}
if(iLength > 0 && iLength <= iMaxLen)
result = SendInternal(pSocketObj, itPtr);
else
result = ERROR_INCORRECT_SIZE;
if(result != NO_ERROR)
::SetLastError(result);
return (result == NO_ERROR);
}
int CUdpServer::SendInternal(TUdpSocketObj* pSocketObj, TItemPtr& itPtr)
{
BOOL bPending;
{
CLocalSafeCounter localcounter(*pSocketObj);
CReentrantCriSecLock locallock(pSocketObj->csSend);
if(!TUdpSocketObj::IsValid(pSocketObj))
return ERROR_OBJECT_NOT_FOUND;
bPending = pSocketObj->IsPending();
pSocketObj->sndBuff.PushBack(itPtr.Detach());
ASSERT(pSocketObj->sndBuff.Length() > 0);
}
if(!bPending && pSocketObj->IsPending())
VERIFY(m_ioDispatcher.SendCommandByIndex(pSocketObj->index, DISP_CMD_SEND, pSocketObj->connID));
return NO_ERROR;
}
void CUdpServer::DetectConnection(PVOID pv)
{
TUdpSocketObj* pSocketObj = (TUdpSocketObj*)pv;
if(TUdpSocketObj::IsValid(pSocketObj))
{
CUdpServer* pServer = (CUdpServer*)pSocketObj->pHolder;
if(pSocketObj->detectFails >= pServer->m_dwDetectAttempts)
VERIFY(m_ioDispatcher.SendCommandByIndex(pSocketObj->index, DISP_CMD_TIMEOUT, pSocketObj->connID));
else
::InterlockedIncrement(&pSocketObj->detectFails);
::ReadTimer(pSocketObj->fdTimer);
}
}
#endif
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

HP-Socket 是一套通用的高性能 TCP/UDP/HTTP 通信框架,包含服务端组件、客户端组件和Agent组件,广泛适用于各种不同应用场景的 TCP/UDP/HTTP 通信系统,提供 C/C++、C#、Delphi、E(易语言)、Java、Python 等编程语言接口。HP-Socket 对通信层实现完全封装,应用程序不必关注通信层的任何细节;HP-Socket 提供基于事件通知模型的 API 接口,能非常简单高效地整合到新旧应用程序中。
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/githubdby/HP-Socket.git
git@gitee.com:githubdby/HP-Socket.git
githubdby
HP-Socket
HP-Socket
dev
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /