1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 module async_client;
20 
21 import std.exception;
22 import std.stdio;
23 import thrift.async.libevent;
24 import thrift.async.socket;
25 import thrift.base;
26 import thrift.codegen.async_client;
27 import thrift.protocol.binary;
28 import thrift.transport.buffered;
29 
30 import tutorial.Calculator;
31 import tutorial.tutorial_types;
32 
33 void main() {
34   auto asyncManager = new TLibeventAsyncManager;
35 
36   // If we are done, gracefully stop the async manager to avoid hanging on
37   // appplication shutdown.
38   scope (exit) asyncManager.stop();
39 
40   auto socket = new TAsyncSocket(asyncManager, "localhost", 9090);
41   auto client = new TAsyncClient!Calculator(
42     socket,
43     new TBufferedTransportFactory,
44     new TBinaryProtocolFactory!TBufferedTransport
45   );
46 
47   socket.open();
48 
49   // Invoke all the methods.
50   auto pingResult = client.ping();
51 
52   auto addResult = client.add(1, 1);
53 
54   auto work = Work();
55   work.op = Operation.DIVIDE;
56   work.num1 = 1;
57   work.num2 = 0;
58   auto quotientResult = client.calculate(1, work);
59 
60   work.op = Operation.SUBTRACT;
61   work.num1 = 15;
62   work.num2 = 10;
63   auto diffResult = client.calculate(1, work);
64 
65   auto logResult = client.getStruct(1);
66 
67   // Await the responses.
68   pingResult.waitGet();
69   writeln("ping()");
70 
71   int sum = addResult.waitGet();
72   writefln("1 + 1 = %s", sum);
73 
74   try {
75     quotientResult.waitGet();
76     writeln("Whoa we can divide by 0");
77   } catch (InvalidOperation io) {
78     writeln("Invalid operation: " ~ io.why);
79   }
80 
81   writefln("15 - 10 = %s", diffResult.waitGet());
82 
83   // TFuture is implicitly convertible to the result type via »alias this«,
84   // for which it (eagerly, of course) awaits completion.
85   writefln("Check log: %s", logResult.value);
86 }