helper.cpp 1012 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #include "helper.h"
  2. #include "impl.h"
  3. #include "network.h"
  4. namespace NCoro {
  5. bool TryConnect(const TString& host, ui16 port, TDuration timeout) {
  6. bool connected = false;
  7. auto f = [&connected, &host, port, timeout](TCont* c) {
  8. TSocketHolder socket;
  9. TNetworkAddress address(host, port);
  10. connected = (0 == NCoro::ConnectT(c, socket, address, timeout));
  11. };
  12. TContExecutor e(128 * 1024);
  13. e.Create(f, "try_connect");
  14. e.Execute();
  15. return connected;
  16. }
  17. bool WaitUntilConnectable(const TString& host, ui16 port, TDuration timeout) {
  18. const TInstant deadline = timeout.ToDeadLine();
  19. for (size_t i = 1; Now() < deadline; ++i) {
  20. const TDuration waitTime = TDuration::MilliSeconds(100) * i * i;
  21. SleepUntil(Min(Now() + waitTime, deadline));
  22. if (TryConnect(host, port, waitTime)) {
  23. return true;
  24. }
  25. }
  26. return false;
  27. }
  28. }