thrift -r --gen c_glib ./tutorial.thrift
#include <glib.h> #include <glib-object.h> #include <thrift/c_glib/protocol/thrift_protocol.h> #include <thrift/c_glib/protocol/thrift_binary_protocol.h> #include <thrift/c_glib/transport/thrift_transport.h> #include <thrift/c_glib/transport/thrift_buffered_transport.h> #include <thrift/c_glib/transport/thrift_socket.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <calculator.h> // static ThriftSocket *socket = NULL; static ThriftTransport *transport = NULL; static ThriftProtocol *protocol = NULL; static CalculatorClient *client = NULL; static CalculatorIf *iface = NULL; int thrift_init(const char *hostname, int port) { printf("Initializing Thrift client (server=%s:%d)...\n", hostname, port); g_type_init(); GError *error = NULL; socket = THRIFT_SOCKET(g_object_new(THRIFT_TYPE_SOCKET, "hostname", hostname, "port", port, &error)); if (error) { printf("Failed to create thrift socket: %s\n", error->message); g_error_free(error); return -1; } transport = THRIFT_TRANSPORT(g_object_new(THRIFT_TYPE_BUFFERED_TRANSPORT, "transport", socket, &error)); if (error) { printf("Failed to create thrift transport: %s\n", error->message); g_error_free(error); return -1; } protocol = THRIFT_PROTOCOL(g_object_new(THRIFT_TYPE_BINARY_PROTOCOL, "transport", transport, &error)); if (error) { printf("Failed to create thrift binary protocol: %s\n", error->message); g_error_free(error); return -1; } client = CALCULATOR_CLIENT(g_object_new(TYPE_CALCULATOR_CLIENT, "input_protocol", protocol, "output_protocol", protocol, &error)); if (error) { printf("Failed to create thrift client: %s\n", error->message); g_error_free(error); return -1; } iface = CALCULATOR_IF(client); thrift_transport_open(transport, &error); // if (error) { printf("Failed to open thrift connection: %s\n", error->message); g_error_free(error); return -1; } return socket->sd; // . }
GError *error = NULL; gint32 result = 0; calculator_client_add(iface, &result, 4, 3, &error);
int main() { int socket = -1; if ((socket = thrift_init("localhost", 9090)) >= 0) { GError *error = NULL; calculator_client_send_add(iface, 4, 3, &error); if (error) { // g_error_free(error); return -1; } struct pollfd fds; fds.fd = socket; fds.events = POLLIN; fds.revents = 0; if (poll(&fds, 1, 5000 /*5 */) > 0) { if (fds.revents & POLLIN) { gint32 result = 0; calculator_client_recv_add(iface, &result, &error); // 7 result if (error) { // g_error_free(error); return -1; } } } return 0; } return -1; }
void thrift_destroy() { if (transport) { thrift_transport_close(transport, NULL); g_object_unref(transport); } if (client) { g_object_unref(client); } if (protocol) { g_object_unref(protocol); } if (socket) { g_object_unref(socket); } }
Source: https://habr.com/ru/post/236345/
All Articles