Thrift tutorial(python server and php client)

定义IDL文件hello.thrift

struct User {
	1: string firstname
	2: string lastname
}

exception UserException {
	1: i32 error_code,
	2: string error_msg
}

service UserManager {
	void ping(),
	string get_user(1:string firstname,2:string lastname) throws(1:UserException e),
	oneway void clear_list()
}
生成python和php文件

thrift -r --gen php hello.thrift
thrift -r --gen py hello.thrift
python_server.py

#!/usr/bin/env python

import sys
sys.path.append('./gen-py')

from hello import UserManager
from hello.ttypes import *

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

from daemon import runner

class UserManagerHandler:
	def __init__(self):
		pass

	def ping(self):
		print 'Welcome To Thrift...'

	def get_user(self, firstname, lastname):
		if firstname == '':
			raise UserException(1, 'firstname is empty')
		if lastname == '':
			raise UserException(2, 'lastname is empty')
		return lastname+' '+firstname+'!'

class App:
	def __init__(self):
		self.stdin_path = '/dev/null'
		self.stdout_path = '/dev/null'
		self.stderr_path = '/dev/tty'
		self.pidfile_path = '/tmp/tmp123456.pid'
		self.pidfile_timeout = 5
	
	def run(self):
		handler = UserManagerHandler()
		processor = UserManager.Processor(handler)
		transport = TSocket.TServerSocket(port=9090)
		tfactory = TTransport.TBufferedTransportFactory()
		pfactory = TBinaryProtocol.TBinaryProtocolFactory()
		server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
		print 'Starting the server...'
		server.serve()
				
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
php_client.php

#!/usr/bin/env php
<?php
$GLOBALS['THRIFT_ROOT'] = '/usr/lib/php';

require_once $GLOBALS['THRIFT_ROOT'].'/Thrift.php';
require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/THttpClient.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php';

require_once './gen-php/hello/UserManager.php';

try {
	$socket = new TSocket('localhost', 9090);
	$transport = new TBufferedTransport($socket, 1024, 1024);
	$protocol = new TBinaryProtocol($transport);
	$client = new UserManagerClient($protocol);

	$transport->open();
	$client->ping();
	printf("%s\n", $client->get_user('World', 'Hello'));

} catch (UserException $e) {
	echo $e->error_msg;
}
测试

chmod a+x python_server.py
chmod a+x php_client.php
./python_server.py start
./php_client.php
Hello World!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值