lizongbo at 618119.com 工作,生活,Android,前端,Linode,Ubuntu,nginx,java,apache,tomcat,Resin,mina,Hessian,XMPP,RPC

2009年01月15日

基于apache mina 2.0.0 M4和google Protocol Buffers 2.0.3的java RPC实例(5.Server端的IoHandler)

Filed under: Java — 标签:, , , , — lizongbo @ 00:49

接上一篇: http://618119.com/archives/2009/01/15/129.html
ProtobufRPCServerSessionHandler.

[code]
package com.lizongbo.protobufrpc;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import java.util.Map;
import java.util.HashMap;
import com.google.protobuf.Service;
import com.lizongbo.mobileqq.UserInfoServiceImpl;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Descriptors.MethodDescriptor;
import com.google.protobuf.Message;
import com.google.protobuf.RpcCallback;
import com.lizongbo.mobileqq.UserInfoServiceRpcController;

public class ProtobufRPCServerSessionHandler extends IoHandlerAdapter {
/**存放service实例的map*/
private Map servicemap = new HashMap();
public ProtobufRPCServerSessionHandler() {
UserInfoServiceImpl userInfoServiceImpl = new UserInfoServiceImpl();
String serviceName = userInfoServiceImpl.getDescriptor().getFullName();
System.out.println(“put “+serviceName);
servicemap.put(serviceName, userInfoServiceImpl);
}

public void messageReceived(final IoSession session, Object message) throws
Exception {
System.out.println(“messageReceived == ” + session.getClass());
ProtobufRPCRequest req = (ProtobufRPCRequest) message;
Service service = servicemap.get(req.getServiceName());
System.out.println(“service========”+service);
System.out.println(“req.getMethodName()==”+req.getMethodName());
MethodDescriptor md = service.getDescriptorForType().
findMethodByName(req.getMethodName());
System.out.println(“md=========”+md);
Message request = service.
getRequestPrototype(md).
newBuilderForType().mergeFrom(
req.getRequestMessage()).build();

service.callMethod(md,
new UserInfoServiceRpcController(), request,
new
RpcCallback() {
public void run(Message response) {
System.out.println(
“write socket for:” +
response.
toString());
byte[] data = response.
toByteArray();
try {
ProtobufRPCResponse res = new ProtobufRPCResponse();
res.setResponseMessage(data);
session.write(res);
} catch (Exception ex) {
ex.printStackTrace();
}

}
}
);
}

public void exceptionCaught(IoSession session, Throwable cause) throws
Exception {
System.out.println(“exceptionCaught == ” + session.getClass());
cause.printStackTrace();

}
}

[/code]

没有评论 »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress