native_client.cpp 2.31 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Copyright (c) 2017 Baidu, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// A thrift client sending requests to server every 1 second.

#include <gflags/gflags.h>
18 19 20 21 22 23
#include "gen-cpp/EchoService.h"
#include "gen-cpp/echo_types.h"
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>

24 25
#include <butil/logging.h>

26 27 28 29 30 31
// _THRIFT_STDCXX_H_ is defined by thrift/stdcxx.h which was added since thrift 0.11.0
#ifndef THRIFT_STDCXX
 #if defined(_THRIFT_STDCXX_H_)
 # define THRIFT_STDCXX apache::thrift::stdcxx
 #else
 # define THRIFT_STDCXX boost
32
 # include <boost/make_shared.hpp>
33 34 35
 #endif
#endif

36 37
DEFINE_string(server, "0.0.0.0", "IP Address of server");
DEFINE_int32(port, 8019, "Port of server");
38 39 40

int main(int argc, char **argv) {

41 42 43
    // Parse gflags. We recommend you to use gflags as well.
    google::ParseCommandLineFlags(&argc, &argv, true);

44
    THRIFT_STDCXX::shared_ptr<apache::thrift::transport::TSocket> socket(
wangxuefeng's avatar
wangxuefeng committed
45
        new apache::thrift::transport::TSocket(FLAGS_server, FLAGS_port));
46
    THRIFT_STDCXX::shared_ptr<apache::thrift::transport::TTransport> transport(
wangxuefeng's avatar
wangxuefeng committed
47
        new apache::thrift::transport::TFramedTransport(socket));
48
    THRIFT_STDCXX::shared_ptr<apache::thrift::protocol::TProtocol> protocol(
wangxuefeng's avatar
wangxuefeng committed
49
        new apache::thrift::protocol::TBinaryProtocol(transport));
50 51 52 53 54

    example::EchoServiceClient client(protocol);
    transport->open();

    example::EchoRequest req;
55 56
    req.__set_data("hello");
    req.__set_need_by_proxy(10);
57 58

    example::EchoResponse res;
59

60
    while (1) {
61 62
        try {
            client.Echo(res, req);
63
            LOG(INFO) << "Req=" << req << " Res=" << res;
64 65 66
        } catch (std::exception& e) {
            LOG(ERROR) << "Fail to rpc, " << e.what();
        }
67
        sleep(1);
68
    }
69
    transport->close();
70

71
    return 0;
72
}