sessionCreate(IoSession)
IoSession对象被创建时的回调,一般用于进行会话初始化操作。注意:与sessionOpened(IoSession)不同,IoSession对象的创建并不意味着对应底层TCP连接的建立,而仅仅代表字面意思:一个IoSession对象被创建出来了。
sessionOpened(IoSession)
IoSession对象被打开时回调。在TCP中,该事件是在TCP连接建立时触发,一般可用于发起连接建立的握手、认证等操作。
sessionIdle(IoSession,IdleStatus)
IoSession对象超时时回调。当一个IoSession对象在指定的超时时常内没有读写事件发生,就会触发该事件,一般可用于通知服务器断开长时间闲置的连接等处理。具体的超时设置可由 IoService.setWriteIdleTime(int) ,IoService.setReadIdleTime(int) ,IoService.setBothIdleTime(int)设置。
messageReceived(IoSession,Object)
当接收到IoSession对Client发送的数据时回调。
messageSent(IoSession,Object)
当发送给IoSession对Client的数据发送成功时回调。
exceptionCaught(IoSession,Throwable)
当会话过程中出现异常时回调,通常用于错误处理。
session.write(Object)方法是一个异步方法,对该方法的调用并不会阻塞,而是向Mina投递一个异步的写操作,并返回一个可用于对已投递异步写操作进行控制的WriteFuture对象。例如:调用WriteFuture的await()或awaitUninterruptibly(),可由同步等待该异步操作的完成。
在I/O处理器中实现业务逻辑的时候,对于简单的情况,一般只需要在messageReceived中对传入的消息进行处理。如果需要写回数据到对等体,用IoSession.write()即可。
另外的情况,client和server的通信协议比较复杂,client是有状态变迁的,这时可用Mina提供的状态机实现,可使用IO处理器的实现更加简单。
androidpn中XmppIoHandler源代码:
- packageorg.androidpn.server.xmpp.net;
- importjava.util.Map;
- importjava.util.concurrent.ConcurrentHashMap;
- importorg.androidpn.server.xmpp.XmppServer;
- importorg.apache.commons.logging.Log;
- importorg.apache.commons.logging.LogFactory;
- importorg.apache.mina.core.service.IoHandler;
- importorg.apache.mina.core.session.IdleStatus;
- importorg.apache.mina.core.session.IoSession;
- importorg.dom4j.io.XMPPPacketReader;
- importorg.jivesoftware.openfire.net.MXParser;
- importorg.jivesoftware.openfire.nio.XMLLightweightParser;
- importorg.xmlpull.v1.XmlPullParserException;
- importorg.xmlpull.v1.XmlPullParserFactory;
- /**
- *Thisclassistocreatenewsessions,destroysessionsanddeliver
- *receivedXMLstanzastotheStanzaHandler.
- *
- *@authorSehwanNoh(devnoh@gmail.com)
- */
- publicclassXmppIoHandlerimplementsIoHandler{
- privatestaticfinalLoglog=LogFactory.getLog(XmppIoHandler.class);
- publicstaticfinalStringXML_PARSER="XML_PARSER";
- privatestaticfinalStringCONNECTION="CONNECTION";
- privatestaticfinalStringSTANZA_HANDLER="STANZA_HANDLER";
- privateStringserverName;
- privatestaticMap<Integer,XMPPPacketReader>parsers=newConcurrentHashMap<Integer,XMPPPacketReader>();
- privatestaticXmlPullParserFactoryfactory=null;
- static{
- try{
- factory=XmlPullParserFactory.newInstance(
- MXParser.class.getName(),null);
- factory.setNamespaceAware(true);
- }catch(XmlPullParserExceptione){
- log.error("Errorcreatingaparserfactory",e);
- }
- }
- /**
- *Constructor.Settheservernamefromserverinstance.
- */
- protectedXmppIoHandler(){
- serverName=XmppServer.getInstance().getServerName();
- }
- /**
- *InvokedfromanI/Oprocessorthreadwhenanewconnectionhasbeencreated.
- */
- publicvoidsessionCreated(IoSessionsession)throwsException{
- log.debug("sessionCreated()...");
- }
- /**
- *Invokedwhenaconnectionhasbeenopened.
- */
- publicvoidsessionOpened(IoSessionsession)throwsException{
- log.debug("sessionOpened()...");
- log.debug("remoteAddress="+session.getRemoteAddress());
- //CreateanewXMLparser
- XMLLightweightParserparser=newXMLLightweightParser("UTF-8");
- session.setAttribute(XML_PARSER,parser);
- //Createanewconnection
- Connectionconnection=newConnection(session);
- session.setAttribute(CONNECTION,connection);
- session.setAttribute(STANZA_HANDLER,newStanzaHandler(serverName,
- connection));
- }
- /**
- *Invokedwhenaconnectionisclosed.
- */
- publicvoidsessionClosed(IoSessionsession)throwsException{
- log.debug("sessionClosed()...");
- Connectionconnection=(Connection)session.getAttribute(CONNECTION);
- connection.close();
- }
- /**
- *InvokedwiththerelatedIdleStatuswhenaconnectionbecomesidle.
- */
- publicvoidsessionIdle(IoSessionsession,IdleStatusstatus)
- throwsException{
- log.debug("sessionIdle()...");
- Connectionconnection=(Connection)session.getAttribute(CONNECTION);
- if(log.isDebugEnabled()){
- log.debug("Closingconnectionthathasbeenidle:"+connection);
- }
- connection.close();
- }
- /**
- *Invokedwhenanyexceptionisthrown.
- */
- publicvoidexceptionCaught(IoSessionsession,Throwablecause)
- throwsException{
- log.debug("exceptionCaught()...");
- log.error(cause);
- }
- /**
- *Invokedwhenamessageisreceived.
- */
- publicvoidmessageReceived(IoSessionsession,Objectmessage)
- throwsException{
- log.debug("messageReceived()...");
- log.debug("RCVD:"+message);
- //Getthestanzahandler
- StanzaHandlerhandler=(StanzaHandler)session
- .getAttribute(STANZA_HANDLER);
- //GettheXMPPpacketparser
- inthashCode=Thread.currentThread().hashCode();
- XMPPPacketReaderparser=parsers.get(hashCode);
- if(parser==null){
- parser=newXMPPPacketReader();
- parser.setXPPFactory(factory);
- parsers.put(hashCode,parser);
- }
- //Thestanzahandlerprocessesthemessage
- try{
- handler.process((String)message,parser);
- }catch(Exceptione){
- log.error(
- "Closingconnectionduetoerrorwhileprocessingmessage:"
- +message,e);
- Connectionconnection=(Connection)session
- .getAttribute(CONNECTION);
- connection.close();
- }
- }
- /**
- *InvokedwhenamessagewrittenbyIoSession.write(Object)issentout.
- */
- publicvoidmessageSent(IoSessionsession,Objectmessage)throwsException{
- log.debug("messageSent()...");
- }
- }
XmppIoHandler在加载的时候创建相关的xml解析工厂。
sessionOpened:在连接打开时候创建相关的xml的解析器和Handler处理器。
sessionClosed:关闭相关的连接。
sessionIdle:关闭相关的连接。
messageReceived:获取相关的xml解析器和handler处理器处理相关的消息。