if ( getType() == ConnectionType.SOCKET_S2S ) { connectionAcceptor = new LegacyConnectionAcceptor( generateConnectionConfiguration() ); } else { connectionAcceptor = new MINAConnectionAcceptor( generateConnectionConfiguration() ); }
LegacyConnectionAcceptor是个废弃的类,但不知道为什么s2s还要用这个呢?看了看实现,LegacyConnectionAcceptor就是起了一个线程,在线程里建了一个ServerSocket。可能以后还是会迁移这部分代码吧。
在connectionAcceptor中会根据类型创建一个ConnectionHandler用于实现具体的业务功能,而ConnectionHandler都是基于org.apache.mina.core.service.IoHandlerAdapter派生的类,而IoHandlerAdapter又是IoHandler的适配接口,所以实质上就是IoHandler。下面是类继承关系:
在这些Handler里完成的主要是每个连接打开、关闭和数据收发等操作的处理。而其中比较关键的一个步骤就是在sessionOpened中设置了StanzeHandler,而每种ConnectionHandler都有自己的StanzeHandler实现。以ClientConnectionHandler为例子,其中ClientConnectionHandler复写了父类的createStanzaHandler方法,这里面
@Override StanzaHandler createStanzaHandler(NIOConnection connection) { return new ClientStanzaHandler(XMPPServer.getInstance().getPacketRouter(), connection); }
这里使用的是clientStanzaHandler,表示是客户端的数据节处理者。而最终的createStanzaHandler调用是在父类ConnectionHandler的sessionOpened完成的,
@Override public void sessionOpened(IoSession session) throws Exception { // Create a new XML parser for the new connection. The parser will be used by the XMPPDecoder filter. final XMLLightweightParser parser = new XMLLightweightParser(StandardCharsets.UTF_8); session.setAttribute(XML_PARSER, parser); // Create a new NIOConnection for the new session final NIOConnection connection = createNIOConnection(session); session.setAttribute(CONNECTION, connection); session.setAttribute(HANDLER, createStanzaHandler(connection)); // Set the max time a connection can be idle before closing it. This amount of seconds // is divided in two, as Openfire will ping idle clients first (at 50% of the max idle time) // before disconnecting them (at 100% of the max idle time). This prevents Openfire from // removing connections without warning. final int idleTime = getMaxIdleTime() / 2; if (idleTime > 0) { session.getConfig().setIdleTime(IdleStatus.READER_IDLE, idleTime); } }