您好,登錄后才能下訂單哦!
Apache MINA中怎么進行對象傳輸,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
利用Apache MINA來傳遞對象,這對了MINA來說非常容易,并且這也是Java網絡編程中很常用的應用。其實對于MINA傳遞對象來說,如果看過前一篇文章的話,只要在其中做少許改動就可以實現對象傳遞,但這里考慮到例子的完整性,還是給出了全部代碼示例。
首先看兩個用來傳遞的Java對象MyRequestObject和MyResponseObject,很簡單只是實現了Serializable接口罷了。
package com.google.code.garbagecan.minastudy.sample3; import java.io.Serializable; public class MyRequestObject implements Serializable { private static final long serialVersionUID = 1L; private String name; private String value; public MyRequestObject(String name, String value) { this.name = name; this.value = value; } 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; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Request [name: " + name + ", value: " + value + "]"); return sb.toString(); } } package com.google.code.garbagecan.minastudy.sample3; import java.io.Serializable; public class MyResponseObject implements Serializable { private static final long serialVersionUID = 1L; private String name; private String value; public MyResponseObject(String name, String value) { this.name = name; this.value = value; } 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; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Response [name: " + name + ", value: " + value + "]"); return sb.toString(); } }
看看Server端的代碼
package com.google.code.garbagecan.minastudy.sample3; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; import org.apache.mina.filter.logging.LoggingFilter; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyServer { private static final Logger logger = LoggerFactory.getLogger(MyServer.class); public static void main(String[] args) { IoAcceptor acceptor = new NioSocketAcceptor(); acceptor.getFilterChain().addLast("logger", new LoggingFilter()); acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); acceptor.setHandler(new IoHandlerAdapter() { @Override public void sessionCreated(IoSession session) throws Exception { } @Override public void sessionOpened(IoSession session) throws Exception { } @Override public void sessionClosed(IoSession session) throws Exception { } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { } @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { logger.error(cause.getMessage(), cause); session.close(true); } @Override public void messageReceived(IoSession session, Object message) throws Exception { logger.info("Received " + message); MyRequestObject myReqOjb = (MyRequestObject) message; MyResponseObject myResObj = new MyResponseObject(myReqOjb.getName(), myReqOjb.getValue()); session.write(myResObj); } @Override public void messageSent(IoSession session, Object message) throws Exception { logger.info("Sent " + message); } }); try { acceptor.bind(new InetSocketAddress(10000)); } catch (IOException ex) { logger.error(ex.getMessage(), ex); } } }
1. 首先創建I/O Service,這里使用的是NioSocketAcceptor類來創建了一個IoAcceptor實例。
2. 創建I/O Filter Chain,這里使用了兩個個IoFilter,一個是LoggingFilter用來記錄日志和打印事件消息,另一個是ProtocolCodecFilter實例用來編碼數據,這里使用了ObjectSerializationCodecFactory類來序列化或反序列化數據成java對象。
3. 創建I/O Handler,這里主要看一下messageReceived方法,其總接收了MyRequestObject對象,然后又發送了一個MyResponseObject對象給Client端。
4. ***就是讓IoAcceptor類實例綁定端口實現監聽。
看看Client端的代碼
package com.google.code.garbagecan.minastudy.sample3; import java.net.InetSocketAddress; import org.apache.mina.core.RuntimeIoException; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.service.IoConnector; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; import org.apache.mina.filter.logging.LoggingFilter; import org.apache.mina.transport.socket.nio.NioSocketConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyClient { private static final Logger logger = LoggerFactory.getLogger(MyClient.class); public static void main(String[] args) { IoConnector connector = new NioSocketConnector(); connector.setConnectTimeoutMillis(10 * 1000); connector.getFilterChain().addLast("logger", new LoggingFilter()); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); connector.setHandler(new IoHandlerAdapter() { @Override public void sessionCreated(IoSession session) throws Exception { } @Override public void sessionOpened(IoSession session) throws Exception { MyRequestObject myObj = new MyRequestObject("my name", "my value"); session.write(myObj); } @Override public void sessionClosed(IoSession session) throws Exception { } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { } @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { logger.error(cause.getMessage(), cause); session.close(true); } @Override public void messageReceived(IoSession session, Object message) throws Exception { MyResponseObject myResObj = (MyResponseObject) message; logger.info("Received " + myResObj); session.close(true); } @Override public void messageSent(IoSession session, Object message) throws Exception { logger.info("Sent " + message); } }); IoSession session = null; try { ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 10000)); future.awaitUninterruptibly(); session = future.getSession(); } catch (RuntimeIoException e) { logger.error(e.getMessage(), e); } session.getCloseFuture().awaitUninterruptibly(); connector.dispose(); } }
1. 首先創建I/O Service,這里使用的是NioSocketConnector類來創建了一個IoConnector實例,并設置連接超時為10秒。
2. 創建I/O Filter Chain,和服務器端同樣設置了兩個IoFilter,一個是LoggingFilter用來記錄日志和打印事件消息,另一個是ProtocolCodecFilter實例用來編碼數據,這里也使用了ObjectSerializationCodecFactory類來序列化或反序列化數據成java對象。
3. 創建I/O Handler,主要看一下sessionOpened方法,其中在會話建立事件中發送了MyRequestObject對象,然后在messageReceived方法中又接受了MyResponseObject對象。
4. ***就是IoConnector實例類連接遠端的Server。
下面測試一下上面的程序,首先運行MyServer類,然后運行MyClient類,就可以分別在各自的終端上看到事件日志以及發送/接收的對象了。
看完上述內容,你們掌握Apache MINA中怎么進行對象傳輸的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。