brew install thrift
pip install thrift
helloworld.thrift
string ping(),
string
say(1:string msg)
}執行以下命令:
thrift -gen py helloworld.thrift
它會在當前目錄的gen
目錄下生成以下檔案:
├── gen-py
│ ├── __init__.py
│ └── helloworld
│ ├── helloworld-remote
│ ├── helloworld.py
│ ├── __init__.py
│ ├── constants.py
│ ├── ttypes.py
server.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import sys
from helloworld import helloworld
from helloworld.ttypes import *
from thrift.transport import tsocket
from thrift.transport import ttransport
from thrift.protocol import tbinaryprotocol
from thrift.server import tserver
class
helloworldhandler:
defping
(self):
return
"pong"
defsay
(self, msg):
ret = "received: " + msg
print ret
return ret
#建立服務端
handler = helloworldhandler()
processor = helloworld.processor(handler)
#監聽埠
transport = tsocket.tserversocket("localhost", 9090)
#選擇傳輸層
tfactory = ttransport.tbufferedtransportfactory()
#選擇傳輸協議
pfactory = tbinaryprotocol.tbinaryprotocolfactory()
#建立服務端
server = tserver.t******server(processor, transport, tfactory, pfactory)
print
"starting thrift server in python..."
server.serve()
print
"done!"
client.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from helloworld import helloworld #引入客戶端類
from thrift import thrift
from thrift.transport import tsocket
from thrift.transport import ttransport
from thrift.protocol import tbinaryprotocol
try:
#建立socket
transport = tsocket.tsocket('localhost', 9090)
#選擇傳輸層,這塊要和服務端的設定一致
transport = ttransport.tbufferedtransport(transport)
#選擇傳輸協議,這個也要和服務端保持一致,否則無法通訊
protocol = tbinaryprotocol.tbinaryprotocol(transport)
#建立客戶端
client = helloworld.client(protocol)
transport.open()
print
"client - ping"
print
"server - " + client.ping()
print
"client - say"
msg = client.say("hello!")
print
"server - " + msg
#關閉傳輸
transport.close()
#捕獲異常
except thrift.texception, ex:
print
"%s" % (ex.message)
ref
VS2008 thrift簡單使用示例
thrift 0.9.3 編譯依賴第三方庫 boost 1 53 0 openssl idl 檔案 student.thrift struct student service serv 使用如下命令生成相關 thrift 0.9.3.exe r gen cpp d test demothrift s...
Thrift使用教程
structrequeststruct 定義乙個請求包結構 structresponsestruct 定義乙個響應包結構 service sharedservice 定義乙個收發資料服務介面 1 先把從thrift指令碼編譯得到的 和編譯好的library新增到你的專案裡。2 client端使用例子...
Thrift 各種server 使用模式
最近在專案中需要把客戶端的一些資訊傳送到伺服器上,聽起來是個很簡單的需求,但是實際考慮下,覺得如果自己手工實現,工作量也不小,而且盡是些繁瑣且無聊的事情,遂考慮用現成的庫來實現。對比了protocol buffer與thrift後,本著偷懶到底的原則,選擇了thrift,因為thrift本身提供了r...