Fix copyright lines
[folly.git] / folly / io / async / test / SocketClient.cpp
1 /*
2  * Copyright 2016-present 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 <iostream>
19
20 #include <folly/ExceptionWrapper.h>
21 #include <folly/portability/GFlags.h>
22
23 using namespace folly;
24
25 DEFINE_string(host, "localhost", "Host");
26 DEFINE_int32(port, 0, "port");
27 DEFINE_bool(tfo, false, "enable tfo");
28 DEFINE_string(msg, "", "Message to send");
29 DEFINE_bool(ssl, false, "use ssl");
30 DEFINE_int32(timeout_ms, 0, "timeout");
31 DEFINE_int32(sendtimeout_ms, 0, "send timeout");
32 DEFINE_int32(num_writes, 1, "number of writes");
33
34 int main(int argc, char** argv) {
35   gflags::ParseCommandLineFlags(&argc, &argv, true);
36
37   if (FLAGS_port == 0) {
38     LOG(ERROR) << "Must specify port";
39     exit(EXIT_FAILURE);
40   }
41
42   // Prep the socket
43   EventBase evb;
44   AsyncSocket::UniquePtr socket;
45   if (FLAGS_ssl) {
46     auto sslContext = std::make_shared<SSLContext>();
47     socket = AsyncSocket::UniquePtr(new AsyncSSLSocket(sslContext, &evb));
48   } else {
49     socket = AsyncSocket::UniquePtr(new AsyncSocket(&evb));
50   }
51   socket->detachEventBase();
52
53   if (FLAGS_tfo) {
54 #if FOLLY_ALLOW_TFO
55     socket->enableTFO();
56 #endif
57   }
58
59   if (FLAGS_sendtimeout_ms != 0) {
60     socket->setSendTimeout(FLAGS_sendtimeout_ms);
61   }
62
63   // Keep this around
64   auto sockAddr = socket.get();
65
66   BlockingSocket sock(std::move(socket));
67   SocketAddress addr;
68   addr.setFromHostPort(FLAGS_host, FLAGS_port);
69   sock.setAddress(addr);
70   std::chrono::milliseconds timeout(FLAGS_timeout_ms);
71   sock.open(timeout);
72   LOG(INFO) << "connected to " << addr.getAddressStr();
73
74   for (int32_t i = 0; i < FLAGS_num_writes; ++i) {
75     sock.write((const uint8_t*)FLAGS_msg.data(), FLAGS_msg.size());
76   }
77
78   LOG(INFO) << "TFO attempted: " << sockAddr->getTFOAttempted();
79   LOG(INFO) << "TFO finished: " << sockAddr->getTFOFinished();
80   LOG(INFO) << "TFO success: " << sockAddr->getTFOSucceded();
81
82   std::array<char, 1024> buf;
83   int32_t bytesRead = 0;
84   while ((bytesRead = sock.read((uint8_t*)buf.data(), buf.size())) != 0) {
85     std::cout << std::string(buf.data(), bytesRead);
86   }
87
88   sock.close();
89   return 0;
90 }