Add support for TFO connections
[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
28 int main(int argc, char** argv) {
29   gflags::ParseCommandLineFlags(&argc, &argv, true);
30
31   if (FLAGS_port == 0) {
32     LOG(ERROR) << "Must specify port";
33     exit(EXIT_FAILURE);
34   }
35
36   // Prep the socket
37   EventBase evb;
38   AsyncSocket::UniquePtr socket(new AsyncSocket(&evb));
39   socket->detachEventBase();
40
41   if (FLAGS_tfo) {
42 #if FOLLY_ALLOW_TFO
43     socket->enableTFO();
44 #endif
45   }
46
47   // Keep this around
48   auto sockAddr = socket.get();
49
50   BlockingSocket sock(std::move(socket));
51   SocketAddress addr;
52   addr.setFromHostPort(FLAGS_host, FLAGS_port);
53   sock.setAddress(addr);
54   sock.open();
55   LOG(INFO) << "connected to " << addr.getAddressStr();
56
57   sock.write((const uint8_t*)FLAGS_msg.data(), FLAGS_msg.size());
58
59   LOG(ERROR) << "TFO attempted: " << sockAddr->getTFOAttempted();
60   LOG(ERROR) << "TFO finished: " << sockAddr->getTFOFinished();
61
62   std::array<char, 1024> buf;
63   int32_t bytesRead = 0;
64   while ((bytesRead = sock.read((uint8_t*)buf.data(), buf.size())) != 0) {
65     std::cout << std::string(buf.data(), bytesRead);
66   }
67
68   sock.close();
69   return 0;
70 }