student.thrift
struct Student {
1:i32 id,
2:string name,
3:i16 age,
}
service PutStudentInfoService {
void put(1:Student s);
}
serv
server.cpp
#include<iostream>
#include "PutStudentInfoService.h"
#include <protocol/TBinaryProtocol.h>
#include <server/TSimpleServer.h>
#include <transport/TServerSocket.h>
#include <transport/TBufferTransports.h>
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using boost::shared_ptr;
using namespace std;
//using namespace ;
class PutStudentInfoServiceHandler : virtual public PutStudentInfoServiceIf {
public:
PutStudentInfoServiceHandler() {
// Your initialization goes here
}
void put(const Student& s) {
cout<<"服务器即将存储客户端传来的信息: id="<<s.id<<" name="<<s.name<<" age="<<s.age<<endl;
students.push_back(s);
cout<<"现在总共有 "<<students.size()<<"个学生的信息! 分别为:"<<endl;
for(vector<Student>::iterator it=students.begin(); it!=students.end();it++)
cout<<"id="<<s.id<<" name="<<s.name<<" age="<<s.age<<endl;
}
private:
vector<Student> students;
};
int main(int argc, char **argv) {
int port = 9090;
shared_ptr<PutStudentInfoServiceHandler> handler(new PutStudentInfoServiceHandler());
shared_ptr<TProcessor> processor(new PutStudentInfoServiceProcessor(handler));
shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);
// TThreadedServer server(processor, serverTransport, transportFactory, protocolFactory);
/*
shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(15);
shared_ptr<PosixThreadFactory> threadFactory
= shared_ptr<PosixThreadFactory>(new PosixThreadFactory());
threadManager->threadFactory(threadFactory);
threadManager->start();
printf("start.../n");
TThreadPoolServer server(processor,serverTransport,transportFactory, protocolFactory, threadManager);
*/
server.serve();
return 0;
}
client.cpp
#include"PutStudentInfoService.h"
#include<transport/TSocket.h>
#include<transport/TBufferTransports.h>
#include<protocol/TBinaryProtocol.h>
#include<iostream>
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace std;
int main(int argc ,char **argv){
boost::shared_ptr<TSocket> socket(new TSocket("localhost" ,9090));
boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
PutStudentInfoServiceClient client(protocol);
transport ->open();
Student s;
s.id=201031003100;
s.name="chenwei";
s.age=23;
cout<<"客户端即将要向服务器提交的信息为: id="<<s.id<<" name="<<s.name<<" age="<<s.age<<endl;
client.put(s);
transport ->close();
return 0;
}