Preface: for thrift/RPC installation, refer to the previous article, which describes the use of thrift/rpc.
1. define your own service interfaces as follows:
1. The content of the music. Thrift file is as follows:
Namespace CPP shansj
Struct music_info {
1: i32 song_id;
2: String song_name;
3: String song_singer;
4: String song_album;
}
Note: A struct is defined in a diagram, and you want to call it through the client to transmit the struct to the server.
2. Define service interfaces as follows:
The content of the song_rpc.thrift file is as follows:
Namespace CPP shansj
Include "music. Thrift"
Service musicservlet {
Void sendmessage (1: List <music. music_info> music );
}
Reprinted please indicate the source: zhujian blog, http://blog.csdn.net/linyanwen99/article/details/8281508
3. Compile the generated code as follows:
Thrift -- Gen CPP music. Thrift
Thrift -- Gen CPP song_rpc.thrift
In the Gen-CPP folder, the corresponding files are generated as follows:
2. Write the server code as follows:
# Include <vector>
# Include <boost/shared_ptr.hpp>
# Include <thrift/protocol/tbinaryprotocol. h>
# Include <thrift/Server/tsimpleserver. h>
# Include <thrift/transport/tserversocket. h>
# Include <thrift/transport/tbuffertransports. h>
# Include "../Gen-CPP/musicservlet. H"
Using namespace: Apache: thrift;
Using namespace: Apache: thrift: Protocol;
Using namespace: Apache: thrift: Transport;
Using namespace: Apache: thrift: server;
Using namespace shansj;
Using boost: shared_ptr;
Class musicservlethandler: virtual public musicservletif {
Public:
Musicservlethandler (){
}
Void sendmessage (const STD: vector <music_info> & music ){
Printf ("[musicservlethandler: sendmessage] invoke \ n ");
Printf ("song_id: % d \ n", music [0]. song_id );
Printf ("song_name: % s \ n", music [0]. song_name.c_str ());
Printf ("song_singer: % s \ n", music [0]. song_singer.c_str ());
Printf ("song_album: % s \ n", music [0]. song_album.c_str ());
}
};
Note: 1. The sendmessage method in this class is just a schematic, simply print the data sent from the client.
2. The methods defined in the service interface must be fully implemented on the server. For the specific reason, you can check the generated code to find out.
Int main (INT argc, char ** argv ){
Int Port = 5555;
Shared_ptr <musicservlethandler> handler (New musicservlethandler ());
Shared_ptr <tprocessor> processor (New musicservletprocessor (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 );
Server. Serve ();
Return 0;
}
3. The running result is as follows:
Reprinted please indicate the source: zhujian blog, http://blog.csdn.net/linyanwen99/article/details/8281508