您好,登錄后才能下訂單哦!
Apache MINA中怎么進(jìn)行對象傳輸,相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
利用Apache MINA來傳遞對象,這對了MINA來說非常容易,并且這也是Java網(wǎng)絡(luò)編程中很常用的應(yīng)用。其實(shí)對于MINA傳遞對象來說,如果看過前一篇文章的話,只要在其中做少許改動(dòng)就可以實(shí)現(xiàn)對象傳遞,但這里考慮到例子的完整性,還是給出了全部代碼示例。
首先看兩個(gè)用來傳遞的Java對象MyRequestObject和MyResponseObject,很簡單只是實(shí)現(xiàn)了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. 首先創(chuàng)建I/O Service,這里使用的是NioSocketAcceptor類來創(chuàng)建了一個(gè)IoAcceptor實(shí)例。
2. 創(chuàng)建I/O Filter Chain,這里使用了兩個(gè)個(gè)IoFilter,一個(gè)是LoggingFilter用來記錄日志和打印事件消息,另一個(gè)是ProtocolCodecFilter實(shí)例用來編碼數(shù)據(jù),這里使用了ObjectSerializationCodecFactory類來序列化或反序列化數(shù)據(jù)成java對象。
3. 創(chuàng)建I/O Handler,這里主要看一下messageReceived方法,其總接收了MyRequestObject對象,然后又發(fā)送了一個(gè)MyResponseObject對象給Client端。
4. ***就是讓IoAcceptor類實(shí)例綁定端口實(shí)現(xiàn)監(jiān)聽。
看看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. 首先創(chuàng)建I/O Service,這里使用的是NioSocketConnector類來創(chuàng)建了一個(gè)IoConnector實(shí)例,并設(shè)置連接超時(shí)為10秒。
2. 創(chuàng)建I/O Filter Chain,和服務(wù)器端同樣設(shè)置了兩個(gè)IoFilter,一個(gè)是LoggingFilter用來記錄日志和打印事件消息,另一個(gè)是ProtocolCodecFilter實(shí)例用來編碼數(shù)據(jù),這里也使用了ObjectSerializationCodecFactory類來序列化或反序列化數(shù)據(jù)成java對象。
3. 創(chuàng)建I/O Handler,主要看一下sessionOpened方法,其中在會(huì)話建立事件中發(fā)送了MyRequestObject對象,然后在messageReceived方法中又接受了MyResponseObject對象。
4. ***就是IoConnector實(shí)例類連接遠(yuǎn)端的Server。
下面測試一下上面的程序,首先運(yùn)行MyServer類,然后運(yùn)行MyClient類,就可以分別在各自的終端上看到事件日志以及發(fā)送/接收的對象了。
看完上述內(nèi)容,你們掌握Apache MINA中怎么進(jìn)行對象傳輸?shù)姆椒藛??如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。