前言
继上文,我们实现了一个基本的接口 match.thrift
namespace cpp match_service struct User { 1: i32 id, 2: string name, 3: i32 score } service Match { i32 add_user(1: User user, 2: string info), i32 remove_user(1: User user, 2: string info), } 复制代码
基于这个接口我们可以实现一个如图的简单匹配系统:
用 python 作为客户端远程调用进行用户的添加或者删除,cpp 作为服务端进行用户的匹配,虽然省略了数据存储,但也算是一个最小的匹配系统的实现。
生成
通过 match.thrift 分别生成 python 和 cpp 代码:
thrift -r --gen cpp match.thrift thrift -r --gen py match.thrift 复制代码
生成的代码分别放置在 gen-cpp 以及 gen-py 文件夹下, 我们重新梳理一下文件结构:
mv gen-cpp match_server mv gen-py match_client cd match_server mv Match_server.skeleton.cpp main.cpp cd ../match_client/match rm Match-remote
基本功能
跟 上篇文章 一样,我们先测试跑通:
// match_server/main.cpp ... #include <iostream> ... class MatchHandler : virtual public MatchIf { public: ... int32_t add_user(const User& user, const std::string& info) { printf("add_user\n"); // 添加了 return 0 return 0; } int32_t remove_user(const User& user, const std::string& info) { printf("remove_user\n"); // 添加了 return 0 return 0; } }; int main(int argc, char **argv) { ... TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory); // 输出测试 std::cout << "Start match server 😎" << std::endl; server.serve(); return 0; } 复制代码
测试,看到输出证明成功:
# 编译,连接,运行 g++ -c *.cpp g++ *.o -o main -lthrift ./main 复制代码
然后是客户端代码,新建 client.py,参考官方示例
from match import Match from match.ttypes import User from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol def main(): # Make socket transport = TSocket.TSocket('localhost', 9090) # Buffering is critical. Raw sockets are very slow transport = TTransport.TBufferedTransport(transport) # Wrap in a protocol protocol = TBinaryProtocol.TBinaryProtocol(transport) # Create a client to use the protocol encoder client = Match.Client(protocol) # Connect! transport.open() # 测试 user = User(1, "mancuoj", 1500) client.add_user(user, "") # Close! transport.close() if __name__=="__main__": main() 复制代码
开启服务端,然后运行 client.py,你会看到如图的输出:
具体代码可以查看github,骨架已经搭好,下篇我们继续😎


