将mina整合到tomcat中

时间:2022-12-20 19:54:57

webgame中的聊天模块采用前台flash,后台java,socket来进行通讯。后台是自己写的socket server。但存在很多问题,与spring不方便整合,部署的时候要分开部署。自己写的还存在效率问题。所以想到了apache mina。如果用mina的话就会提高socket服务器的效率。又在网上查到一些mina与tomcat整合的资料,自己就动手开始进行整合

首先在pom.xml中加入
<!-- mina and mix spring -->
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId>
<version>2.0.0-M3</version>
</dependency>
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-integration-spring</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-integration-beans</artifactId>
<version>2.0.0-M3</version>
</dependency>

运行ant通过maven取得相应的jar包。然后加入spring的配置,让mina和spring整合在一起。

<beans>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.net.SocketAddress">
<bean class="org.apache.mina.integration.beans.InetSocketAddressEditor" />
</entry>
</map>
</property>
</bean>

<!-- The IoHandler implementation -->
<bean id="minaHandler" class="com.game.MinaProtocolHandler"/>

<!-- the IoFilters -->
<bean id="executorFilter" class="org.apache.mina.filter.executor.ExecutorFilter" />

<bean id="mdcInjectionFilter" class="org.apache.mina.filter.logging.MdcInjectionFilter">
<constructor-arg value="remoteAddress" />
</bean>

<bean id="codecFilter" class="org.apache.mina.filter.codec.ProtocolCodecFilter">
<constructor-arg>
<bean class="org.apache.mina.filter.codec.textline.TextLineCodecFactory" />
</constructor-arg>
</bean>

<bean id="loggingFilter" class="org.apache.mina.filter.logging.LoggingFilter" />

<!-- The non-SSL filter chain. -->
<bean id="filterChainBuilder" class="org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder">
<property name="filters">
<map>
<entry key="executor" value-ref="executorFilter" />
<entry key="mdcInjectionFilter" value-ref="mdcInjectionFilter" />
<entry key="codecFilter" value-ref="codecFilter" />
<entry key="loggingFilter" value-ref="loggingFilter" />
</map>
</property>
</bean>

<!-- The IoAcceptor which binds to port 8888 server side -->
<bean id="minaAcceptor" class="org.apache.mina.transport.socket.nio.NioSocketAcceptor"
init-method="bind" destroy-method="unbind">
<property name="defaultLocalAddress" value=":8888" />
<property name="handler" ref="minaHandler" />
<property name="reuseAddress" value="true" />
<property name="filterChainBuilder" ref="filterChainBuilder" />
</bean>

</beans>

其中com.game.MinaProtocolHandler是我要实现的类,新建类MinaProtocolHandler继承IoHandlerAdapter,代码如下

public void messageReceived(IoSession session, Object message) {
String msg = (String) message;
System.out.println("Server Received: " + msg);
session.write("Send msg: " + msg);
}

public void sessionIdle(IoSession session, IdleStatus status) {
session.close();
}

public void exceptionCaught(IoSession session, Throwable cause) {
session.close();
}

启动tomcat,就会开启一个8888的端口,进入命令行输入telnet 127.0.0.1 8888看看