sockpool.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include "sockpool.h"
  2. void SetCommonSockOpts(SOCKET sock, const struct sockaddr* sa) {
  3. SetSockOpt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
  4. if (!sa || sa->sa_family == AF_INET) {
  5. sockaddr_in s_in;
  6. s_in.sin_family = AF_INET;
  7. s_in.sin_addr.s_addr = INADDR_ANY;
  8. s_in.sin_port = 0;
  9. if (bind(sock, (struct sockaddr*)&s_in, sizeof(s_in)) == -1) {
  10. warn("bind");
  11. }
  12. } else if (sa->sa_family == AF_INET6) {
  13. sockaddr_in6 s_in6(*(const sockaddr_in6*)sa);
  14. Zero(s_in6.sin6_addr);
  15. s_in6.sin6_port = 0;
  16. if (bind(sock, (const struct sockaddr*)&s_in6, sizeof s_in6) == -1) {
  17. warn("bind6");
  18. }
  19. } else {
  20. Y_ASSERT(0);
  21. }
  22. SetNoDelay(sock, true);
  23. }
  24. TPooledSocket TSocketPool::AllocateMore(TConnectData* conn) {
  25. TCont* cont = conn->Cont;
  26. while (true) {
  27. TSocketHolder s(NCoro::Socket(Addr_->Addr()->sa_family, SOCK_STREAM, 0));
  28. if (s == INVALID_SOCKET) {
  29. ythrow TSystemError(errno) << TStringBuf("can not create socket");
  30. }
  31. SetCommonSockOpts(s, Addr_->Addr());
  32. SetZeroLinger(s);
  33. const int ret = NCoro::ConnectD(cont, s, Addr_->Addr(), Addr_->Len(), conn->DeadLine);
  34. if (ret == EINTR) {
  35. continue;
  36. } else if (ret) {
  37. ythrow TSystemError(ret) << TStringBuf("can not connect(") << cont->Name() << ')';
  38. }
  39. THolder<TPooledSocket::TImpl> res(new TPooledSocket::TImpl(s, this));
  40. s.Release();
  41. if (res->IsOpen()) {
  42. return res.Release();
  43. }
  44. }
  45. }