您的位置:首页 > 其它

实现两个独立服务器之间的通信

2013-01-13 14:26 267 查看
在实施项目的过程中,一个项目一般是不会只是架构在一个服务器上,针对项目的各个部分分布在各自独立的服务器中。

例如手机网游的服务器架构:

View Code

public void exec(HttpRequest request, HttpResponse response) {
// TODO Auto-generated method stub
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
try {
ChannelBuffer cb = request.getContent();
byte[] b = cb.array();
ByteArrayInputStream bis = new ByteArrayInputStream(b);
ObjectInputStream data = new ObjectInputStream(bis);
String className = data.readUTF();
String methodName = data.readUTF();
int count = data.read();
Class c = Class.forName(className);
//#debug
System.out.println(className + "." + methodName);
List<Class> cl = new ArrayList<Class>();
List<Object> vl = new ArrayList<Object>();
for (int i = 0; i < count ; i++) {
cl.add((Class) data.readObject());
vl.add(data.readObject());
}
Class[] cls = new Class[cl.size()];
cl.toArray(cls);
String mk = toMethodKey(className, methodName, cls);
Method m = methods.get(mk);
if (m == null) {
m = c.getMethod(methodName, cls);
methods.put(mk, m);
}
Object[] values = new Object[vl.size()];
vl.toArray(values);
Object o = m.invoke(c, values);
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(o);
oos.flush();
response.getContent().writeBytes(bos.toByteArray());
cl.clear();
vl.clear();
} catch (Exception e) {
e.printStackTrace();
try {
response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);//.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeUTF(e.getClass() + "." + e.getMessage());
bos.flush();
response.getContent().writeBytes(bos.toByteArray());
bos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
if (oos != null)
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


本人技术水平不足,希望各位朋友予以指点,共同进步,Eamil:zhong678*yeah.net , QQ:982925115
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: