fix flaky ConnectTFOTimeout and ConnectTFOFallbackTimeout tests
[folly.git] / folly / io / async / test / SocketClient.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <folly/io/async/test/BlockingSocket.h>
17
18 #include <folly/ExceptionWrapper.h>
19 #include <gflags/gflags.h>
20
21 using namespace folly;
22
23 DEFINE_string(host, "localhost", "Host");
24 DEFINE_int32(port, 0, "port");
25 DEFINE_bool(tfo, false, "enable tfo");
26 DEFINE_string(msg, "", "Message to send");
27 DEFINE_bool(ssl, false, "use ssl");
28
29 int main(int argc, char** argv) {
30   gflags::ParseCommandLineFlags(&argc, &argv, true);
31
32   if (FLAGS_port == 0) {
33     LOG(ERROR) << "Must specify port";
34     exit(EXIT_FAILURE);
35   }
36
37   // Prep the socket
38   EventBase evb;
39   AsyncSocket::UniquePtr socket;
40   if (FLAGS_ssl) {
41     auto sslContext = std::make_shared<SSLContext>();
42     socket = AsyncSocket::UniquePtr(new AsyncSSLSocket(sslContext, &evb));
43   } else {
44     socket = AsyncSocket::UniquePtr(new AsyncSocket(&evb));
45   }
46   socket->detachEventBase();
47
48   if (FLAGS_tfo) {
49 #if FOLLY_ALLOW_TFO
50     socket->enableTFO();
51 #endif
52   }
53
54   // Keep this around
55   auto sockAddr = socket.get();
56
57   BlockingSocket sock(std::move(socket));
58   SocketAddress addr;
59   addr.setFromHostPort(FLAGS_host, FLAGS_port);
60   sock.setAddress(addr);
61   sock.open();
62   LOG(INFO) << "connected to " << addr.getAddressStr();
63
64   sock.write((const uint8_t*)FLAGS_msg.data(), FLAGS_msg.size());
65
66   LOG(ERROR) << "TFO attempted: " << sockAddr->getTFOAttempted();
67   LOG(ERROR) << "TFO finished: " << sockAddr->getTFOFinished();
68
69   std::array<char, 1024> buf;
70   int32_t bytesRead = 0;
71   while ((bytesRead = sock.read((uint8_t*)buf.data(), buf.size())) != 0) {
72     std::cout << std::string(buf.data(), bytesRead);
73   }
74
75   sock.close();
76   return 0;
77 }