ApacheMina:ObjectSerializationCodecFactory的例子
1. 定义发送的RequestObject和返回的ResponseObject
RequestObject.java
public class RequestObject implements Serializable {private static final long serialVersionUID = 8891436114296586399L;private int id;private String name;private String description;private String others;public RequestObject(int id, String name, String description, String others) {super();this.id = id;this.name = name;this.description = description;this.others = others;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public String getOthers() {return others;}public void setOthers(String others) {this.others = others;}@Overridepublic String toString() {return "RequestObject [id=" + id + ", name=" + name + ", description="+ description + ", others=" + others + "]";}}
public class ResponseObject implements Serializable {private static final long serialVersionUID = -6783592807728197249L;private int id;private String name;private String value;private String remarks;public ResponseObject(int id, String name, String value, String remarks) {super();this.id = id;this.name = name;this.value = value;this.remarks = remarks;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getValue() {return value;}public void setValue(String value) {this.value = value;}public String getRemarks() {return remarks;}public void setRemarks(String remarks) {this.remarks = remarks;}@Overridepublic String toString() {return "ResponseObject [id=" + id + ", name=" + name + ", value="+ value + ", remarks=" + remarks + "]";}}
public class DemoObjectServer {/** * @param args * @throws IOException */public static void main(String[] args) throws IOException {final int PORT = 9123;// objects used to listen for incoming connectionIoAcceptor acceptor = new NioSocketAcceptor();// filters:// 1. log all informationacceptor.getFilterChain().addLast("logger", new LoggingFilter());// 2. translate binary or protocol specific data into message objectacceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));// define the handler used to service client connections and the requests for the current timeacceptor.setHandler(new DemoObjectServerHandler());//NioSocketAcceptor configuration: for the socket that will be used to accept connections from clientacceptor.getSessionConfig().setReadBufferSize(2048);acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);// define the handler class and bind the NioSocketAcception to a portacceptor.bind(new InetSocketAddress(PORT));}}
public class DemoObjectServerHandler extends IoHandlerAdapter {public DemoObjectServerHandler(){super();}@Overridepublic void messageReceived(IoSession session, Object obj) throws Exception {System.out.println("message received");RequestObject ro = (RequestObject) obj;System.out.println("request body:" + ro.toString());String _name = "request_" + ro.getId();String _remarks = "description is " + ro.getDescription() + ", and others is " + ro.getOthers();ResponseObject rpo = new ResponseObject(ro.getId(),_name, ro.getName(), _remarks);session.write(rpo);}@Overridepublic void exceptionCaught(IoSession session, Throwable cause)throws Exception {super.exceptionCaught(session, cause);session.close(true);}}
public class DemoObjectClient {/** * @param args * @throws InterruptedException */public static void main(String[] args) throws InterruptedException {// create a connector NioSocketConnector connector = new NioSocketConnector(); //create a fitler chain connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); connector.getFilterChain().addLast("logger", new LoggingFilter()); // create iohandler //DemoTimeClientHandler handler = new DemoTimeClientHandler("i am jeanjeanfang, hello dear!"); connector.setHandler(new DemoObjectClientHandler()); //connector.setHandler(new ClientSessionHandler(values)); // bind to server IoSession session; for (;;) { try { ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 9123)); future.awaitUninterruptibly(); session = future.getSession(); break; } catch (RuntimeIoException e) { System.err.println("Failed to connect."); e.printStackTrace(); Thread.sleep(5000); } } // wait until the summation is done session.getCloseFuture().awaitUninterruptibly(); connector.dispose();}}
public class DemoObjectClientHandler extends IoHandlerAdapter {@Overridepublic void exceptionCaught(IoSession session, Throwable t)throws Exception {super.exceptionCaught(session, t);session.close(true);}@Overridepublic void messageReceived(IoSession session, Object obj) throws Exception {System.out.println("message received");ResponseObject ro = (ResponseObject) obj;System.out.println("received obj:" + ro.toString());session.close(true);}@Overridepublic void sessionOpened(IoSession session) throws Exception {System.out.println("session opened");RequestObject ro = new RequestObject(101,"name","des11","others...");session.write(ro);}}