源地址:http://mina.apache.org/mina-project/userguide/ch17-spring-integration/ch17-spring-integration.html
一个mina应用主要包括一下方面:
- One Handler
- Two Filter - Logging Filter and a ProtocolCodec Filter
- NioDatagram Socket
一个mina 服务端的实例程序如下:
public void initialize() throws IOException { // Create an Acceptor NioDatagramAcceptor acceptor = new NioDatagramAcceptor(); // Add Handler acceptor.setHandler(new ServerHandler()); acceptor.getFilterChain().addLast("logging", new LoggingFilter()); acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new SNMPCodecFactory())); // Create Session Configuration DatagramSessionConfig dcfg = acceptor.getSessionConfig(); dcfg.setReuseAddress(true); logger.debug("Starting Server......"); // Bind and be ready to listen acceptor.bind(new InetSocketAddress(DEFAULT_PORT)); logger.debug("Server listening on "+DEFAULT_PORT); }
继承过程如下:
1.设置IO handler。在spring context文件中设置IO handler。
<!-- The IoHandler implementation --> <bean id="trapHandler" class="com.ashishpaliwal.udp.mina.server.ServerHandler">
2.创建过滤器链。
<bean id="snmpCodecFilter" class="org.apache.mina.filter.codec.ProtocolCodecFilter"> <constructor-arg> <bean class="com.ashishpaliwal.udp.mina.snmp.SNMPCodecFactory" /> </constructor-arg> </bean> <bean id="loggingFilter" class="org.apache.mina.filter.logging.LoggingFilter" /> <!-- The filter chain. --> <bean id="filterChainBuilder" class="org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder"> <property name="filters"> <map> <entry key="loggingFilter" value-ref="loggingFilter"/> <entry key="codecFilter" value-ref="snmpCodecFilter"/> </map> </property> </bean>
3.创建socket并设置socket参数
<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 IoAcceptor which binds to port 161 --> <bean id="ioAcceptor" class="org.apache.mina.transport.socket.nio.NioDatagramAcceptor" init-method="bind" destroy-method="unbind"> <property name="defaultLocalAddress" value=":161" /> <property name="handler" ref="trapHandler" /> <property name="filterChainBuilder" ref="filterChainBuilder" /> </bean>
测试程序
public void initializeViaSpring() throws Exception { new ClassPathXmlApplicationContext("trapReceiverContext.xml"); }