Java Socket实战(六)

2014-11-24 10:46:19 · 作者: · 浏览: 8
dler) {
MyResponse response = execute(request);
return handler.handle(response);
}
@Override
public MyResponse execute(MyRequest request) {
MyResponse response = null;
SocketChannel socketChannel = null;
try {
socketChannel = SocketChannel.open();
SocketAddress socketAddress = new InetSocketAddress(host, port);
socketChannel.connect(socketAddress);
sendData(socketChannel, request);
response = receiveData(socketChannel);
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
} finally {
try {
socketChannel.close();
} catch(Exception ex) {}
}
return response;
}
private void sendData(SocketChannel socketChannel, MyRequest myRequest) throws IOException {
byte[] bytes = SerializableUtil.toBytes(myRequest);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
socketChannel.write(buffer);
socketChannel.socket().shutdownOutput();
}
private MyResponse receiveData(SocketChannel socketChannel) throws IOException {
MyResponse myResponse = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
byte[] bytes;
int count = 0;
while ((count = socketChannel.read(buffer)) >= 0) {
buffer.flip();
bytes = new byte[count];
buffer.get(bytes);
baos.write(bytes);
buffer.clear();
}
bytes = baos.toByteArray();
Object obj = SerializableUtil.toObject(bytes);
myResponse = (MyResponse) obj;
socketChannel.close();
} finally {
try {
baos.close();
} catch(Exception ex) {}
}
return myResponse;
}
}
4. 接下来是MyRequest和MyResponse和MyResponseHandler接口,其中MyRequest接口中定义了四个方法,分别用来获取远程业务逻辑实现类,方法名,参数类型列表和参数列表。MyResponse接口定义了一个方法用来从response类中获取结果。MyResponseHandler接口使用范型的方式来获取最终的结果对象。
MyRequest.java
[java]
package com.googlecode.garbagecan.test.socket.sample10;
import java.io.Serializable;
public interface MyRequest extends Serializable {
Class< > getRequestClass();
String getRequestMethod();
Class< >[] getRequestParameterTypes();
Object[] getRequestParameterValues();
}
MyResponse.java
[java]
package com.googlecode.garbagecan.test.socket.sample10;
import java.io.Serializable;
public interface MyResponse extends Serializable {
Object getResult();
}
MyResponseHandler.java
[java]
package com.googlecode.garbagecan.test.socket.sample10;
public interface MyResponseHandler {
T handle(MyResponse response);
}
这几个接口的实现类分别对应MyGenericRequest,MyGenericResponse和MyGenericResponseHandler。
另外这里由于使用的反射类来在服务器端生成service实例,所以目前这里有个限制就是服务器端的Service实现类必须有默认构造函数。当然这是可以重构使其支持更多的方式。比如说支持从工厂方法获取实例,或者根据名字在服务器端直接获取已经创建好的,由于这个例子只是一个简单的原型,所以就不做具体深入的说明和实现了。
MyGenericRequest.jav