标签:imp path tps func client list 需要 提示 sock
python install thrift
# -*- coding: utf-8 -*-
import json
# 调用python安装的thrift依赖包
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
# 调用win10下thrift命令自动生成的依赖包;
# 自动生成的依赖包名为gen-py,但是会报错;
# 所以手动把包名改成gen_py运行成功,这是为什么?
from gen_py.test2 import printService
class TestHandler:
def print_msg(self, msg):
try:
# nodejs传过来的字符串数据
print(msg, type(msg))
# 把字符串数据转成字典格式
msg = json.loads(msg)
print(msg, type(msg))
# 在字典中添加一个键值对
msg[‘email‘] = ‘yun@23.com‘
# 把字典转成字符串后返回给nodejs
return json.dumps(msg)
except Exception as e:
print(e)
# 把异常错误写成字典格式
result = {‘errorType‘: e}
# 把字典转成字符串后返回给nodejs
return json.dumps(result)
# 创建服务端
processor = printService.Processor(TestHandler())
# 监听端口
transport = TSocket.TServerSocket(host=‘127.0.0.1‘, port=8080)
# 选择传输层
tfactory = TTransport.TBufferedTransportFactory()
# 选择传输协议
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
# 创建服务端
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print("Starting thrift server in python...")
server.serve()
npm install thrift -g
-g参数表示全局安装,这样在哪都能用了
// 调用nodejs安装的thrift依赖包
var thrift = require(‘thrift‘);
// 调用win10下thrift命令自动生成的依赖包
var printService = require(‘./gen-nodejs/printService.js‘);
// 配置thrift的connection信息
var connection = thrift.createConnection(host = ‘127.0.0.1‘, port = 8080);
// 根据配置的connection创建client
var client = thrift.createClient(printService, connection);
// 监听connection是否error
connection.on("error", function (e) {
console.log(e);
});
// 定义一个json格式数据
var dic = {
name: "yun",
age: "23"
};
console.log(dic.name);
// 把json数据转成字符串格式
dic = JSON.stringify(dic);
// client调用thrift接口定义好的方法函数
client.print_msg(dic, function (err, res) {
if (err) {
console.log(‘err:‘, err);
} else {
console.log(‘res:‘, res);
};
});
// 问题:如何关闭一个client的connection?
/*
thrift接口定义文件
*/
/*
string print_msg(1:string msg)中的print_msg即为服务端中等待被调用的函数
括号中的1:string msg表示传入的参数为字符串格式,外层的string表示传出的数据为字符串格式
*/
service printService {
string print_msg(1:string msg)
}
命名wahaha.thrift,哇哈哈哈哈(●ˇ?ˇ●)
thrift --gen js:node wahaha.thrift
thrift -r --gen py wahaha.thrift
thrift -out savePath --gen js:node wahaha.thrift
thrift -out savePath --gen py wahaha.thrift
从python服务端到nodejs客户端,记得开两个终端分别运行下面命令哦(●‘?‘●)
python server.py
node client.js
标签:imp path tps func client list 需要 提示 sock
原文地址:https://www.cnblogs.com/yun1233/p/10385376.html