Thrift笔记

Thrift 笔记

参考地址: https://blog.csdn.net/dutsoft/article/details/71178655


hello.thrift文件的内容

service HelloService {
    string say(1:string msg)
}

server.py文件内容如下

import socket
import sys
from hello import HelloService
from hello.ttypes import *

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

# hello服务处理(handler)类
class HelloServiceHandler(object):
    def say(self, msg): # 函数名必须与hello.thrift中定义服务的函数名一样
        ret = "Received: " + msg
        print ret
        return ret

handler = HelloServiceHandler() #构建处理的对象
processor = HelloService.Processor(handler) #运行在服务端的处理器
transport = TSocket.TServerSocket("localhost", 9090)
tfactory = TTransport.TBufferedTransportFactory()  # 传递工厂
pfactory = TBinaryProtocol.TBinaryProtocolFactory() # 协议工厂
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print "Starting thrift server in python..."
server.serve() # 启动服务,并持续接收client发送的数据
print "done!"

client.py文件内容如下

import sys
from hello import HelloService
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

try:
    transport = TSocket.TSocket('localhost', 9090) #连接服务器的socket
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = HelloService.Client(protocol)
    transport.open()
    print "client - say"
    msg = client.say("Hello!")
    print "server - " + msg
    transport.close()

except Thrift.TException, ex:
    print "%s" % (ex.message)

执行的时候 首先运行 server.py脚本,启动服务。然后执行client.py 模拟客户端向服务器发送请求。

猜你喜欢

转载自blog.csdn.net/u012969412/article/details/80186278
今日推荐