public static class Factory implements TProtocolFactory {
public TProtocol getProtocol(TTransport trans) { return new GBKCompactProtocol(trans); }
}
}
客户端实现如下:
[java]
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
public class SpClient {
private TTransport transport = null;
private TProtocol protocol = null;
private SpService.Client client = null;
private String ip = null;
private int port = 0;
private int portNum = 0;
public SpClient(String ip, int port, int portNum) throws TTransportException {
this.ip = ip;
this.port = port;
this.portNum = portNum;
open(ip, port, portNum);
}
/**
* open the connection
*/
private void open(String ip, int port, int portNum) throws TTransportException {
int port = (int) (Math.random() * portNum) + port;
transport = new TSocket(ip, port);
protocol = new GBKCompactProtocol(transport);
client = new SpService.Client(protocol);
try {
transport.open();
} catch (TTransportException te) {
try {
Thread.sleep(10);
transport.open();
} catch (InterruptedException ie) {}
}
}
}
服务端主要代码:
[c++]
int main(int argc, char **argv) {
int port = 9999;
shared_ptr/ handler(new SpServiceHandler() );
shared_ptr/ processor(new SpServiceProcessor(handler));
shared_ptr/ serverTransport(new TServerSocket(port));
shared_ptr/ transportFactory(new TBufferedTransportFactory());
shared_ptr/ protocolFactory(new TCompactProtocolFactory());
int multinum = 100;
shared_ptr/ threadManager = ThreadManager::newSimpleThreadManager(multinum);
shared_ptr/ threadFactory = shared_ptr/(new PosixThreadFactory());
threadManager-/>threadFactory(threadFactory);
threadManager-/>start();
printf("start segmentor server...%d thread\n", multinum);
TThreadPoolServer server(processor, serverTransport, transportFactory, protocolFactory, threadManager);
server.setTimeout(20);
server.serve();
return 0;
}