`
jean7155
  • 浏览: 61778 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

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;
	}
	@Override
	public String toString() {
		return "RequestObject [id=" + id + ", name=" + name + ", description="
				+ description + ", others=" + others + "]";
	}

}


ResponseObject.java
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;
	}


	@Override
	public String toString() {
		return "ResponseObject [id=" + id + ", name=" + name + ", value="
				+ value + ", remarks=" + remarks + "]";
	}

	
}

2. 定义Server端的链接接收和业务处理机制
DemoObjectServer.java
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 connection
		IoAcceptor acceptor = new NioSocketAcceptor();
		
		// filters:
		// 1. log all information
		acceptor.getFilterChain().addLast("logger", new LoggingFilter());
		// 2. translate binary or protocol specific data into message object
		acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
		
		// define the handler used to service client connections and the requests for the current time
		acceptor.setHandler(new DemoObjectServerHandler());
		//NioSocketAcceptor configuration: for the socket that will be used to accept connections from client
		acceptor.getSessionConfig().setReadBufferSize(2048);
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
		
		// define the handler class and bind the NioSocketAcception to a port
		acceptor.bind(new InetSocketAddress(PORT));

	}

}



DemoObjectServerHandler.java
public class DemoObjectServerHandler extends IoHandlerAdapter {
	
	public DemoObjectServerHandler(){
		super();
	}
	
	@Override
	public 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);
		
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		super.exceptionCaught(session, cause);
		
		session.close(true);
	}
	
	
}


3. 定义Client端的链接和业务处理机制
DemoObjectClient.java
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();


		}

	

}


DemoObjectClientHandler.java
public class DemoObjectClientHandler extends IoHandlerAdapter {

	@Override
	public void exceptionCaught(IoSession session, Throwable t)
			throws Exception {
		super.exceptionCaught(session, t);
		session.close(true);
	}

	@Override
	public 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);
		

	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		System.out.println("session opened");
		
		RequestObject ro = new RequestObject(101,"name","des11","others...");
		
		session.write(ro);

	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics