UdpClient.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. /*
  2. * Copyright: JessMA Open Source (ldcsaa@gmail.com)
  3. *
  4. * Author : Bruce Liang
  5. * Website : https://github.com/ldcsaa
  6. * Project : https://github.com/ldcsaa/HP-Socket
  7. * Blog : http://www.cnblogs.com/ldcsaa
  8. * Wiki : http://www.oschina.net/p/hp-socket
  9. * QQ Group : 44636872, 75375912
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. #include "UdpClient.h"
  24. #ifdef _UDP_SUPPORT
  25. BOOL CUdpClient::Start(LPCTSTR lpszRemoteAddress, USHORT usPort, BOOL bAsyncConnect, LPCTSTR lpszBindAddress, USHORT usLocalPort)
  26. {
  27. if(!CheckParams() || !CheckStarting())
  28. return FALSE;
  29. PrepareStart();
  30. m_ccContext.Reset();
  31. BOOL isOK = FALSE;
  32. HP_SOCKADDR addrRemote, addrBind;
  33. if(CreateClientSocket(lpszRemoteAddress, addrRemote, usPort, lpszBindAddress, addrBind))
  34. {
  35. if(BindClientSocket(addrBind, addrRemote, usLocalPort))
  36. {
  37. if(TRIGGER(FirePrepareConnect(m_soClient)) != HR_ERROR)
  38. {
  39. if(ConnectToServer(addrRemote, bAsyncConnect))
  40. {
  41. if(CreateWorkerThread())
  42. isOK = TRUE;
  43. else
  44. SetLastError(SE_WORKER_THREAD_CREATE, __FUNCTION__, ERROR_CREATE_FAILED);
  45. }
  46. else
  47. SetLastError(SE_CONNECT_SERVER, __FUNCTION__, ::WSAGetLastError());
  48. }
  49. else
  50. SetLastError(SE_SOCKET_PREPARE, __FUNCTION__, ENSURE_ERROR_CANCELLED);
  51. }
  52. else
  53. SetLastError(SE_SOCKET_BIND, __FUNCTION__, ::WSAGetLastError());
  54. }
  55. else
  56. SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError());
  57. if(!isOK)
  58. {
  59. m_ccContext.Reset(FALSE);
  60. EXECUTE_RESTORE_ERROR(Stop());
  61. }
  62. return isOK;
  63. }
  64. BOOL CUdpClient::CheckParams()
  65. {
  66. if (((int)m_dwMaxDatagramSize > 0 && m_dwMaxDatagramSize <= MAXIMUM_UDP_MAX_DATAGRAM_SIZE) &&
  67. ((int)m_dwFreeBufferPoolSize >= 0) &&
  68. ((int)m_dwFreeBufferPoolHold >= 0) &&
  69. ((int)m_dwDetectAttempts >= 0) &&
  70. ((int)m_dwDetectInterval >= 1000 || m_dwDetectInterval == 0) )
  71. return TRUE;
  72. SetLastError(SE_INVALID_PARAM, __FUNCTION__, ERROR_INVALID_PARAMETER);
  73. return FALSE;
  74. }
  75. void CUdpClient::PrepareStart()
  76. {
  77. m_itPool.SetItemCapacity(m_dwMaxDatagramSize);
  78. m_itPool.SetPoolSize(m_dwFreeBufferPoolSize);
  79. m_itPool.SetPoolHold(m_dwFreeBufferPoolHold);
  80. m_itPool.Prepare();
  81. }
  82. BOOL CUdpClient::CheckStarting()
  83. {
  84. CSpinLock locallock(m_csState);
  85. if(m_enState == SS_STOPPED)
  86. m_enState = SS_STARTING;
  87. else
  88. {
  89. SetLastError(SE_ILLEGAL_STATE, __FUNCTION__, ERROR_INVALID_STATE);
  90. return FALSE;
  91. }
  92. return TRUE;
  93. }
  94. BOOL CUdpClient::CheckStoping()
  95. {
  96. if(m_enState != SS_STOPPED)
  97. {
  98. CSpinLock locallock(m_csState);
  99. if(HasStarted())
  100. {
  101. m_enState = SS_STOPPING;
  102. return TRUE;
  103. }
  104. }
  105. SetLastError(SE_ILLEGAL_STATE, __FUNCTION__, ERROR_INVALID_STATE);
  106. return FALSE;
  107. }
  108. BOOL CUdpClient::CreateClientSocket(LPCTSTR lpszRemoteAddress, HP_SOCKADDR& addrRemote, USHORT usPort, LPCTSTR lpszBindAddress, HP_SOCKADDR& addrBind)
  109. {
  110. HP_SCOPE_HOST host(lpszRemoteAddress);
  111. if(!::GetSockAddrByHostName(host.addr, usPort, addrRemote))
  112. return FALSE;
  113. if(::IsStrNotEmpty(lpszBindAddress))
  114. {
  115. if(!::sockaddr_A_2_IN(lpszBindAddress, 0, addrBind))
  116. return FALSE;
  117. if(addrRemote.family != addrBind.family)
  118. {
  119. ::WSASetLastError(ERROR_AFNOSUPPORT);
  120. return FALSE;
  121. }
  122. }
  123. m_soClient = socket(addrRemote.family, SOCK_DGRAM, IPPROTO_UDP);
  124. if(m_soClient == INVALID_SOCKET)
  125. return FALSE;
  126. VERIFY(::SSO_ReuseAddress(m_soClient, m_enReusePolicy) == NO_ERROR);
  127. SetRemoteHost(host.name, usPort);
  128. return TRUE;
  129. }
  130. BOOL CUdpClient::BindClientSocket(const HP_SOCKADDR& addrBind, const HP_SOCKADDR& addrRemote, USHORT usLocalPort)
  131. {
  132. if(addrBind.IsSpecified() && usLocalPort == 0)
  133. {
  134. if(::bind(m_soClient, addrBind.Addr(), addrBind.AddrSize()) == SOCKET_ERROR)
  135. return FALSE;
  136. }
  137. else if(usLocalPort != 0)
  138. {
  139. HP_SOCKADDR realBindAddr = addrBind.IsSpecified() ? addrBind : HP_SOCKADDR::AnyAddr(addrRemote.family);
  140. realBindAddr.SetPort(usLocalPort);
  141. if(::bind(m_soClient, realBindAddr.Addr(), realBindAddr.AddrSize()) == SOCKET_ERROR)
  142. return FALSE;
  143. }
  144. m_dwConnID = ::GenerateConnectionID();
  145. return TRUE;
  146. }
  147. BOOL CUdpClient::ConnectToServer(const HP_SOCKADDR& addrRemote, BOOL bAsyncConnect)
  148. {
  149. BOOL isOK = FALSE;
  150. if(bAsyncConnect)
  151. {
  152. VERIFY(::fcntl_SETFL(m_soClient, O_NOATIME | O_NONBLOCK | O_CLOEXEC));
  153. int rc = ::connect(m_soClient, addrRemote.Addr(), addrRemote.AddrSize());
  154. if(IS_NO_ERROR(rc) || IS_IO_PENDING_ERROR())
  155. {
  156. m_nEvents = POLLOUT;
  157. isOK = TRUE;
  158. }
  159. }
  160. else
  161. {
  162. if(::connect(m_soClient, addrRemote.Addr(), addrRemote.AddrSize()) != SOCKET_ERROR)
  163. {
  164. VERIFY(::fcntl_SETFL(m_soClient, O_NOATIME | O_NONBLOCK | O_CLOEXEC));
  165. SetConnected();
  166. if(TRIGGER(FireConnect()) == HR_ERROR)
  167. ::WSASetLastError(ENSURE_ERROR_CANCELLED);
  168. else
  169. {
  170. VERIFY(DetectConnection());
  171. m_nEvents = (SHORT)((m_lsSend.IsEmpty() ? 0 : POLLOUT) | (m_bPaused ? 0 : POLLIN) | POLLRDHUP);
  172. isOK = TRUE;
  173. }
  174. }
  175. }
  176. return isOK;
  177. }
  178. BOOL CUdpClient::Stop()
  179. {
  180. if(!CheckStoping())
  181. return FALSE;
  182. WaitForWorkerThreadEnd();
  183. CheckConnected();
  184. if(m_ccContext.bFireOnClose)
  185. FireClose(m_ccContext.enOperation, m_ccContext.iErrorCode);
  186. if(m_soClient != INVALID_SOCKET)
  187. {
  188. shutdown(m_soClient, SHUT_WR);
  189. closesocket(m_soClient);
  190. m_soClient = INVALID_SOCKET;
  191. }
  192. Reset();
  193. return TRUE;
  194. }
  195. void CUdpClient::Reset()
  196. {
  197. CCriSecLock locallock(m_csSend);
  198. m_evSend.Reset();
  199. m_evRecv.Reset();
  200. m_evStop.Reset();
  201. m_lsSend.Clear();
  202. m_itPool.Clear();
  203. m_rcBuffer.Free();
  204. m_strHost.Empty();
  205. m_usPort = 0;
  206. m_nEvents = 0;
  207. m_dwDetectFails = 0;
  208. m_bPaused = FALSE;
  209. m_enState = SS_STOPPED;
  210. m_evWait.SyncNotifyAll();
  211. }
  212. void CUdpClient::WaitForWorkerThreadEnd()
  213. {
  214. if(!m_thWorker.IsRunning())
  215. return;
  216. if(m_thWorker.IsInMyThread())
  217. m_thWorker.Detach();
  218. else
  219. {
  220. m_evStop.Set();
  221. m_thWorker.Join();
  222. }
  223. }
  224. void CUdpClient::CheckConnected()
  225. {
  226. if(!IsConnected())
  227. return;
  228. if(m_ccContext.bNotify)
  229. ::SendUdpCloseNotify(m_soClient);
  230. SetConnected(FALSE);
  231. }
  232. BOOL CUdpClient::CreateWorkerThread()
  233. {
  234. return m_thWorker.Start(this, &CUdpClient::WorkerThreadProc);
  235. }
  236. UINT WINAPI CUdpClient::WorkerThreadProc(LPVOID pv)
  237. {
  238. ::SetCurrentWorkerThreadName();
  239. TRACE("---------------> Client Worker Thread 0x%08X started <---------------", SELF_THREAD_ID);
  240. OnWorkerThreadStart(SELF_THREAD_ID);
  241. BOOL bCallStop = TRUE;
  242. DWORD dwSize = 4;
  243. DWORD dwIndex = 0;
  244. BOOL bDetect = IsNeedDetect();
  245. FD fdUserEvt = GetUserEvent();
  246. if(bDetect) ++dwSize;
  247. if(IS_VALID_FD(fdUserEvt)) ++dwSize;
  248. pollfd* pfds = CreateLocalObjects(pollfd, dwSize);
  249. pfds[dwIndex++] = {m_soClient, m_nEvents};
  250. pfds[dwIndex++] = {m_evSend.GetFD(), POLLIN};
  251. pfds[dwIndex++] = {m_evRecv.GetFD(), POLLIN};
  252. pfds[dwIndex++] = {m_evStop.GetFD(), POLLIN};
  253. unique_ptr<CTimerEvent> evDetectPtr;
  254. if(bDetect)
  255. {
  256. evDetectPtr.reset(new CTimerEvent());
  257. evDetectPtr->Set(m_dwDetectInterval);
  258. pfds[dwIndex++] = {evDetectPtr->GetFD(), POLLIN};
  259. }
  260. if(IS_VALID_FD(fdUserEvt))
  261. pfds[dwIndex++] = {fdUserEvt, POLLIN};
  262. m_rcBuffer.Malloc(m_dwMaxDatagramSize);
  263. while(HasStarted())
  264. {
  265. int rs = (int)::PollForMultipleObjects(pfds, dwSize);
  266. ASSERT(rs > TIMEOUT);
  267. if(rs <= 0)
  268. {
  269. m_ccContext.Reset(TRUE, SO_UNKNOWN, ::WSAGetLastError());
  270. goto EXIT_WORKER_THREAD;
  271. }
  272. for(DWORD i = 0; i < dwSize; i++)
  273. {
  274. if((1 << i) & rs)
  275. {
  276. SHORT revents = pfds[i].revents;
  277. if(i == 0)
  278. {
  279. if(!ProcessNetworkEvent(revents))
  280. goto EXIT_WORKER_THREAD;
  281. }
  282. else if(i == 1)
  283. {
  284. m_evSend.Reset();
  285. if(!SendData())
  286. goto EXIT_WORKER_THREAD;
  287. }
  288. else if(i == 2)
  289. {
  290. m_evRecv.Reset();
  291. if(!ReadData())
  292. goto EXIT_WORKER_THREAD;
  293. }
  294. else if(i == 3)
  295. {
  296. m_evStop.Reset();
  297. bCallStop = FALSE;
  298. goto EXIT_WORKER_THREAD;
  299. }
  300. else if(i == 4)
  301. {
  302. if(bDetect)
  303. {
  304. evDetectPtr->Reset();
  305. if(!CheckConnection())
  306. goto EXIT_WORKER_THREAD;
  307. }
  308. else
  309. {
  310. if(!OnUserEvent())
  311. {
  312. m_ccContext.Reset(TRUE, SO_CLOSE, ENSURE_ERROR_CANCELLED);
  313. goto EXIT_WORKER_THREAD;
  314. }
  315. }
  316. }
  317. else if(i == 5)
  318. {
  319. if(!OnUserEvent())
  320. {
  321. m_ccContext.Reset(TRUE, SO_CLOSE, ENSURE_ERROR_CANCELLED);
  322. goto EXIT_WORKER_THREAD;
  323. }
  324. }
  325. else
  326. VERIFY(FALSE);
  327. }
  328. }
  329. m_nEvents = (SHORT)((m_lsSend.IsEmpty() ? 0 : POLLOUT) | (m_bPaused ? 0 : POLLIN) | POLLRDHUP);
  330. pfds[0].events = m_nEvents;
  331. }
  332. EXIT_WORKER_THREAD:
  333. OnWorkerThreadEnd(SELF_THREAD_ID);
  334. if(bCallStop && HasStarted())
  335. Stop();
  336. TRACE("---------------> Client Worker Thread 0x%08X stoped <---------------", SELF_THREAD_ID);
  337. return 0;
  338. }
  339. BOOL CUdpClient::CheckConnection()
  340. {
  341. if(m_dwDetectFails++ >= m_dwDetectAttempts)
  342. {
  343. m_ccContext.Reset(TRUE, SO_CLOSE, NO_ERROR, FALSE);
  344. return FALSE;
  345. }
  346. DetectConnection();
  347. return TRUE;
  348. }
  349. BOOL CUdpClient::DetectConnection()
  350. {
  351. int result = NO_ERROR;
  352. if((int)send(m_soClient, nullptr, 0, 0) == SOCKET_ERROR)
  353. {
  354. result = ::WSAGetLastError();
  355. if(result == ERROR_WOULDBLOCK)
  356. result = NO_ERROR;
  357. }
  358. BOOL isOK = (result == NO_ERROR);
  359. if(isOK)
  360. {
  361. TRACE("<C-CNNID: %zu> send 0 bytes (detect package succ)", m_dwConnID);
  362. }
  363. else
  364. {
  365. TRACE("<C-CNNID: %zu> send 0 bytes (detect package fail [%d])", m_dwConnID, result);
  366. }
  367. return isOK;
  368. }
  369. BOOL CUdpClient::ProcessNetworkEvent(SHORT events)
  370. {
  371. BOOL bContinue = TRUE;
  372. if(bContinue && events & POLLERR)
  373. bContinue = HandleClose(events);
  374. if(bContinue && !IsConnected())
  375. bContinue = HandleConnect(events);
  376. if(bContinue && events & POLLIN)
  377. bContinue = HandleRead(events);
  378. if(bContinue && events & POLLOUT)
  379. bContinue = HandleWrite(events);
  380. if(bContinue && events & _POLL_HUNGUP_EVENTS)
  381. bContinue = HandleClose(events);
  382. return bContinue;
  383. }
  384. BOOL CUdpClient::HandleConnect(SHORT events)
  385. {
  386. ASSERT(events & POLLOUT);
  387. int code = ::SSO_GetError(m_soClient);
  388. if(!IS_NO_ERROR(code) || (events & _POLL_ERROR_EVENTS))
  389. {
  390. m_ccContext.Reset(TRUE, SO_CONNECT, code);
  391. return FALSE;
  392. }
  393. if(events & _POLL_HUNGUP_EVENTS)
  394. {
  395. m_ccContext.Reset(TRUE, SO_CONNECT, NO_ERROR);
  396. return FALSE;
  397. }
  398. SetConnected();
  399. if(TRIGGER(FireConnect()) != HR_ERROR)
  400. VERIFY(DetectConnection());
  401. else
  402. {
  403. m_ccContext.Reset(FALSE, SO_CLOSE, ENSURE_ERROR_CANCELLED, FALSE);
  404. return FALSE;
  405. }
  406. return TRUE;
  407. }
  408. BOOL CUdpClient::HandleClose(SHORT events)
  409. {
  410. EnSocketOperation enOperation = SO_CLOSE;
  411. if(events & _POLL_HUNGUP_EVENTS)
  412. enOperation = SO_CLOSE;
  413. else if(events & POLLIN)
  414. enOperation = SO_RECEIVE;
  415. else if(events & POLLOUT)
  416. enOperation = SO_SEND;
  417. m_ccContext.Reset(TRUE, enOperation, ::SSO_GetError(m_soClient));
  418. return FALSE;
  419. }
  420. BOOL CUdpClient::HandleRead(SHORT events)
  421. {
  422. return ReadData();
  423. }
  424. BOOL CUdpClient::HandleWrite(SHORT events)
  425. {
  426. return SendData();
  427. }
  428. BOOL CUdpClient::ReadData()
  429. {
  430. while(TRUE)
  431. {
  432. if(m_bPaused)
  433. break;
  434. int rc = (int)recv(m_soClient, (char*)(BYTE*)m_rcBuffer, m_dwMaxDatagramSize, MSG_TRUNC);
  435. if(rc > 0)
  436. {
  437. m_dwDetectFails = 0;
  438. if(::IsUdpCloseNotify(m_rcBuffer, rc))
  439. {
  440. m_ccContext.Reset(TRUE, SO_CLOSE, NO_ERROR, FALSE);
  441. return FALSE;
  442. }
  443. if(rc > (int)m_dwMaxDatagramSize)
  444. {
  445. m_ccContext.Reset(TRUE, SO_RECEIVE, ERROR_BAD_LENGTH);
  446. return FALSE;
  447. }
  448. if(TRIGGER(FireReceive(m_rcBuffer, rc)) == HR_ERROR)
  449. {
  450. TRACE("<C-CNNID: %zu> OnReceive() event return 'HR_ERROR', connection will be closed !", m_dwConnID);
  451. m_ccContext.Reset(TRUE, SO_RECEIVE, ENSURE_ERROR_CANCELLED);
  452. return FALSE;
  453. }
  454. }
  455. else if(rc == SOCKET_ERROR)
  456. {
  457. int code = ::WSAGetLastError();
  458. if(code == ERROR_WOULDBLOCK)
  459. break;
  460. else
  461. {
  462. m_ccContext.Reset(TRUE, SO_RECEIVE, code);
  463. return FALSE;
  464. }
  465. }
  466. else if(rc == 0)
  467. {
  468. m_dwDetectFails = 0;
  469. TRACE("<C-CNNID: %zu> recv 0 bytes (detect ack package)", m_dwConnID);
  470. }
  471. else
  472. ASSERT(FALSE);
  473. }
  474. return TRUE;
  475. }
  476. BOOL CUdpClient::PauseReceive(BOOL bPause)
  477. {
  478. if(!IsConnected())
  479. {
  480. ::SetLastError(ERROR_INVALID_STATE);
  481. return FALSE;
  482. }
  483. if(m_bPaused == bPause)
  484. return TRUE;
  485. m_bPaused = bPause;
  486. if(!bPause)
  487. return m_evRecv.Set();
  488. return TRUE;
  489. }
  490. BOOL CUdpClient::SendData()
  491. {
  492. BOOL bBlocked = FALSE;
  493. while(m_lsSend.Length() > 0)
  494. {
  495. TItemPtr itPtr(m_itPool);
  496. {
  497. CCriSecLock locallock(m_csSend);
  498. itPtr = m_lsSend.PopFront();
  499. }
  500. if(!itPtr.IsValid())
  501. break;
  502. ASSERT(!itPtr->IsEmpty());
  503. if(!DoSendData(itPtr, bBlocked))
  504. return FALSE;
  505. if(bBlocked)
  506. {
  507. CCriSecLock locallock(m_csSend);
  508. m_lsSend.PushFront(itPtr.Detach());
  509. break;
  510. }
  511. }
  512. return TRUE;
  513. }
  514. BOOL CUdpClient::DoSendData(TItem* pItem, BOOL& bBlocked)
  515. {
  516. int rc = (int)send(m_soClient, (char*)pItem->Ptr(), pItem->Size(), 0);
  517. if(rc > 0)
  518. {
  519. ASSERT(rc == pItem->Size());
  520. if(TRIGGER(FireSend(pItem->Ptr(), rc)) == HR_ERROR)
  521. {
  522. TRACE("<C-CNNID: %zu> OnSend() event should not return 'HR_ERROR' !!", m_dwConnID);
  523. ASSERT(FALSE);
  524. }
  525. }
  526. else if(rc == SOCKET_ERROR)
  527. {
  528. int code = ::WSAGetLastError();
  529. if(code == ERROR_WOULDBLOCK)
  530. bBlocked = TRUE;
  531. else
  532. {
  533. m_ccContext.Reset(TRUE, SO_SEND, code);
  534. return FALSE;
  535. }
  536. }
  537. else
  538. ASSERT(FALSE);
  539. return TRUE;
  540. }
  541. BOOL CUdpClient::DoSend(const BYTE* pBuffer, int iLength, int iOffset)
  542. {
  543. ASSERT(pBuffer && iLength > 0 && iLength <= (int)m_dwMaxDatagramSize);
  544. int result = NO_ERROR;
  545. if(pBuffer && iLength > 0 && iLength <= (int)m_dwMaxDatagramSize)
  546. {
  547. if(IsConnected())
  548. {
  549. if(iOffset != 0) pBuffer += iOffset;
  550. TItemPtr itPtr(m_itPool, m_itPool.PickFreeItem());
  551. itPtr->Cat(pBuffer, iLength);
  552. result = SendInternal(itPtr);
  553. }
  554. else
  555. result = ERROR_INVALID_STATE;
  556. }
  557. else
  558. result = ERROR_INVALID_PARAMETER;
  559. if(result != NO_ERROR)
  560. ::SetLastError(result);
  561. return (result == NO_ERROR);
  562. }
  563. BOOL CUdpClient::SendPackets(const WSABUF pBuffers[], int iCount)
  564. {
  565. ASSERT(pBuffers && iCount > 0);
  566. if(!pBuffers || iCount <= 0)
  567. return ERROR_INVALID_PARAMETER;
  568. if(!IsConnected())
  569. return ERROR_INVALID_STATE;
  570. int result = NO_ERROR;
  571. int iLength = 0;
  572. int iMaxLen = (int)m_dwMaxDatagramSize;
  573. TItemPtr itPtr(m_itPool, m_itPool.PickFreeItem());
  574. for(int i = 0; i < iCount; i++)
  575. {
  576. int iBufLen = pBuffers[i].len;
  577. if(iBufLen > 0)
  578. {
  579. BYTE* pBuffer = (BYTE*)pBuffers[i].buf;
  580. ASSERT(pBuffer);
  581. iLength += iBufLen;
  582. if(iLength <= iMaxLen)
  583. itPtr->Cat(pBuffer, iBufLen);
  584. else
  585. break;
  586. }
  587. }
  588. if(iLength > 0 && iLength <= iMaxLen)
  589. result = SendInternal(itPtr);
  590. else
  591. result = ERROR_INCORRECT_SIZE;
  592. if(result != NO_ERROR)
  593. ::SetLastError(result);
  594. return (result == NO_ERROR);
  595. }
  596. int CUdpClient::SendInternal(TItemPtr& itPtr)
  597. {
  598. int iPending;
  599. {
  600. CCriSecLock locallock(m_csSend);
  601. if(!IsConnected())
  602. return ERROR_INVALID_STATE;
  603. iPending = m_lsSend.Length();
  604. m_lsSend.PushBack(itPtr.Detach());
  605. ASSERT(m_lsSend.Length() > 0);
  606. }
  607. if(iPending == 0 && m_lsSend.Length() > 0) m_evSend.Set();
  608. return NO_ERROR;
  609. }
  610. void CUdpClient::SetLastError(EnSocketError code, LPCSTR func, int ec)
  611. {
  612. TRACE("%s --> Error: %d, EC: %d", func, code, ec);
  613. m_enLastError = code;
  614. ::SetLastError(ec);
  615. }
  616. BOOL CUdpClient::GetLocalAddress(TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort)
  617. {
  618. ASSERT(lpszAddress != nullptr && iAddressLen > 0);
  619. return ::GetSocketLocalAddress(m_soClient, lpszAddress, iAddressLen, usPort);
  620. }
  621. void CUdpClient::SetRemoteHost(LPCTSTR lpszHost, USHORT usPort)
  622. {
  623. m_strHost = lpszHost;
  624. m_usPort = usPort;
  625. }
  626. BOOL CUdpClient::GetRemoteHost(TCHAR lpszHost[], int& iHostLen, USHORT& usPort)
  627. {
  628. BOOL isOK = FALSE;
  629. if(m_strHost.IsEmpty())
  630. return isOK;
  631. int iLen = m_strHost.GetLength() + 1;
  632. if(iHostLen >= iLen)
  633. {
  634. memcpy(lpszHost, CA2CT(m_strHost), iLen * sizeof(TCHAR));
  635. usPort = m_usPort;
  636. isOK = TRUE;
  637. }
  638. iHostLen = iLen;
  639. return isOK;
  640. }
  641. BOOL CUdpClient::GetRemoteHost(LPCSTR* lpszHost, USHORT* pusPort)
  642. {
  643. *lpszHost = m_strHost;
  644. if(pusPort != nullptr)
  645. *pusPort = m_usPort;
  646. return !m_strHost.IsEmpty();
  647. }
  648. #endif