• Spring2.5+MINA2搭建Socket Server


     

    1、下载相应的开发包http://mina.apache.org/,MINA2.0版本包含了spring开发包,还需下载其他相关包,我的工程用到的包如下图:

         

     

    2、配置spring的applicationContext.xml,配置mina服务;

     
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2.   
    3. <beans xmlns="http://www.springframework.org/schema/beans"   
    4.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    5.        xmlns:aop="http://www.springframework.org/schema/aop"   
    6.        xmlns:tx="http://www.springframework.org/schema/tx"   
    7.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
    8.        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   
    9.        http://www.springframework.org/schema/aop   
    10.        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd   
    11.        http://www.springframework.org/schema/tx   
    12.        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
    13.   
    14.     <!-- mina server -->  
    15.     <bean id="serverHandler" class="com.supconit.its.server.handler.ServerHandler" />  
    16.       
    17.     <!-- executorFilter多线程处理 -->  
    18.     <bean id="executorFilter" class="org.apache.mina.filter.executor.ExecutorFilter" />  
    19.       
    20.     <bean id="mdcInjectionFilter" class="org.apache.mina.filter.logging.MdcInjectionFilter">  
    21.         <constructor-arg value="remoteAddress" />  
    22.     </bean>  
    23.       
    24.     <bean id="codecFilter" class="org.apache.mina.filter.codec.ProtocolCodecFilter">  
    25.         <constructor-arg>  
    26.         <!-- <bean class="org.apache.mina.filter.codec.textline.TextLineCodecFactory" />-->  
    27.         <!-- 处理对象流时候用ObjectSerializationCodecFactory -->  
    28.         <!-- <bean class="org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory" /> -->  
    29.             <bean class="com.supconit.its.server.handler.ServerCodeFactory" />  
    30.         </constructor-arg>  
    31.     </bean>  
    32.       
    33.     <bean id="loggingFilter" class="org.apache.mina.filter.logging.LoggingFilter" />  
    34.       
    35.     <bean id="filterChainBuilder" class="org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder">  
    36.         <property name="filters">  
    37.             <map>  
    38.                 <entry key="executor" value-ref="executorFilter" />  
    39.                 <entry key="mdcInjectionFilter" value-ref="mdcInjectionFilter" />  
    40.                 <entry key="codecFilter" value-ref="codecFilter" />  
    41.                 <entry key="loggingFilter" value-ref="loggingFilter" />  
    42.             </map>  
    43.         </property>  
    44.     </bean>  
    45.       
    46.     <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">  
    47.         <property name="customEditors">  
    48.             <map>  
    49.                 <entry key="java.net.SocketAddress">  
    50.                     <bean class="org.apache.mina.integration.beans.InetSocketAddressEditor" />  
    51.                 </entry>  
    52.             </map>  
    53.         </property>  
    54.     </bean>  
    55.   
    56.     <bean id="ioAcceptor" class="org.apache.mina.transport.socket.nio.NioSocketAcceptor" init-method="bind" destroy-method="unbind">  
    57.         <property name="defaultLocalAddress" value=":1235" />  
    58.         <property name="handler" ref="serverHandler" />  
    59.         <property name="filterChainBuilder" ref="filterChainBuilder" />  
    60.         <property name="reuseAddress" value="true" />  
    61.     </bean>  

    3、ServerHandler实现类

     
    1. package com.supconit.its.server.handler;  
    2.   
    3. import java.net.InetSocketAddress;  
    4. import java.util.Collections;  
    5. import java.util.Date;  
    6. import java.util.HashSet;  
    7. import java.util.Set;  
    8.   
    9. import org.apache.log4j.Logger;  
    10. import org.apache.mina.core.service.IoHandlerAdapter;  
    11. import org.apache.mina.core.session.IdleStatus;  
    12. import org.apache.mina.core.session.IoSession;  
    13.   
    14.   
    15. public class ServerHandler extends IoHandlerAdapter {  
    16.   
    17.     private final int IDLE = 300;  
    18.       
    19.      //private final Logger log = LoggerFactory .getLogger(HandlerTwo.class);   
    20.      private final Logger log = Logger.getLogger(ServerHandler.class.getName());  
    21.   
    22.      public static Set<IoSession> sessions = Collections .synchronizedSet(new HashSet<IoSession>());  
    23.        
    24.     /** 
    25.      *  
    26.      */  
    27.     public ServerHandler(){  
    28.           
    29.     }  
    30.   
    31.     @Override  
    32.     public void exceptionCaught(IoSession session, Throwable cause)  
    33.             throws Exception {  
    34.         session.close();  
    35.         //log.debug("session occured exception, so close it.");   
    36.         log.debug("session occured exception, so close it." + cause.getMessage());  
    37.     }  
    38.       
    39.     @Override  
    40.     public void sessionCreated(IoSession session) {  
    41.         //    
    42.         log.debug("remote client ["+session.getRemoteAddress().toString()+"] connected.");  
    43.         session.write("Welcome");  
    44.         sessions.add(session);  
    45.     }  
    46.       
    47.     @Override  
    48.     public void messageReceived(IoSession session, Object message)  
    49.             throws Exception {  
    50.         String str = message.toString();  
    51.         log.debug("Message written..." + str);  
    52.         log.debug("客户端"+((InetSocketAddress) session.getRemoteAddress()).getAddress().getHostAddress()+"连接成功!");  
    53.         /*if (str.trim().equalsIgnoreCase("quit")) { 
    54.             session.close();//  
    55.             return; 
    56.         }*/  
    57.         //Date date = new Date();   
    58.         //session.write(date.toString());//    
    59.         //session.setAttribute(remoteAddress, message);   
    60.           
    61.         session.setAttribute("type", message);  
    62.         String remoteAddress = ((InetSocketAddress) session.getRemoteAddress()).getAddress().getHostAddress();  
    63.         session.setAttribute("ip", remoteAddress);  
    64.           
    65.     }  
    66.   
    67.     @Override  
    68.     public void sessionClosed(IoSession session) throws Exception {  
    69.          log.debug("sessionClosed.");  
    70.         sessions.remove(session);  
    71.     }  
    72.   
    73.     @Override  
    74.     public void sessionIdle(IoSession session, IdleStatus status)  
    75.             throws Exception {  
    76.         log.debug("session idle, so disconnecting......");  
    77.         session.close();  
    78.         log.debug("disconnected.");  
    79.     }  
    80.       
    81.     //    
    82.     @Override  
    83.     public void messageSent(IoSession session, Object message) throws Exception {  
    84.          log.debug("messageSent.");  
    85.         // disconnect an idle client   
    86.         //session.close();   
    87.     }  
    88.       
    89.     @Override  
    90.     public void sessionOpened(IoSession session) throws Exception {  
    91.         log.debug("sessionOpened.");  
    92.         //   
    93.         session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, IDLE);  
    94.     }  
    95.   
    96. }  

    4、过滤器ServerCodeFactory

     
    1. package com.supconit.its.server.handler;  
    2.   
    3. import java.nio.charset.Charset;  
    4.   
    5. import org.apache.mina.core.session.IoSession;  
    6. import org.apache.mina.filter.codec.ProtocolCodecFactory;  
    7. import org.apache.mina.filter.codec.ProtocolDecoder;  
    8. import org.apache.mina.filter.codec.ProtocolEncoder;  
    9. import org.apache.mina.filter.codec.textline.LineDelimiter;  
    10. import org.apache.mina.filter.codec.textline.TextLineDecoder;  
    11. import org.apache.mina.filter.codec.textline.TextLineEncoder;  
    12.   
    13. public  class ServerCodeFactory implements ProtocolCodecFactory {  
    14.   
    15.         private final TextLineEncoder encoder;  
    16.         private final TextLineDecoder decoder;  
    17.         /*final static char endchar = 0x1a;*/  
    18.         final static char endchar = 0x0d;  
    19.         public ServerCodeFactory() {  
    20.             this(Charset.forName("gb2312"));  
    21.         }  
    22.         public ServerCodeFactory(Charset charset) {  
    23.              encoder = new TextLineEncoder(charset, LineDelimiter.UNIX);     
    24.              decoder = new TextLineDecoder(charset, LineDelimiter.AUTO);     
    25.              }  
    26.   
    27.         @Override  
    28.         public ProtocolDecoder getDecoder(IoSession session) throws Exception {  
    29.             // TODO Auto-generated method stub   
    30.             return decoder;  
    31.         }  
    32.         @Override  
    33.         public ProtocolEncoder getEncoder(IoSession session) throws Exception {  
    34.             // TODO Auto-generated method stub   
    35.             return encoder;  
    36.         }  
    37.         public int getEncoderMaxLineLength() {  
    38.             return encoder.getMaxLineLength();  
    39.         }  
    40.         public void setEncoderMaxLineLength(int maxLineLength) {  
    41.             encoder.setMaxLineLength(maxLineLength);  
    42.         }  
    43.         public int getDecoderMaxLineLength() {  
    44.             return decoder.getMaxLineLength();  
    45.         }  
    46.         public void setDecoderMaxLineLength(int maxLineLength) {  
    47.             decoder.setMaxLineLength(maxLineLength);  
    48.         }  
    49.   
    50. }  

    5、启动spring+mina socket server;

     
    1. package com.supconit.its.server.test;  
    2.   
    3. import org.springframework.context.support.ClassPathXmlApplicationContext;  
    4.   
    5. public class Test {  
    6.   
    7.     /** 
    8.      * @param args 
    9.      */  
    10.     public static void main(String[] args) {  
    11.         ClassPathXmlApplicationContext ct =    new ClassPathXmlApplicationContext("applicationContext.xml");     
    12.   
    13.     }  
    14.   
    15. }  

    6、客户端测试ClintTest

     
    1. package com.supconit.its.server.test;  
    2.   
    3. import java.net.InetSocketAddress;  
    4. import java.nio.charset.Charset;  
    5.   
    6. import org.apache.mina.core.future.ConnectFuture;  
    7. import org.apache.mina.filter.codec.ProtocolCodecFilter;  
    8. import org.apache.mina.filter.codec.textline.TextLineCodecFactory;  
    9. import org.apache.mina.filter.logging.LoggingFilter;  
    10. import org.apache.mina.transport.socket.nio.NioSocketConnector;  
    11.   
    12. import com.supconit.its.server.handler.ServerHandler;  
    13.   
    14.   
    15.   
    16. public class ClintTest {  
    17.   
    18.     /** 
    19.      * @param args 
    20.      */  
    21.     public static void main(String[] args) {  
    22.         NioSocketConnector connector = new NioSocketConnector();   
    23.         connector.getFilterChain().addLast( "logger"new LoggingFilter() );   
    24.         //connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "GBK" )))); //   
    25.         connector.getFilterChain().addLast( "codec"new ProtocolCodecFilter( new TextLineCodecFactory( )));   
    26.         connector.setConnectTimeout(1);   
    27.         connector.setHandler(new ServerHandler());//   
    28.         ConnectFuture cf = connector.connect(   
    29.         new InetSocketAddress("127.0.0.1"1235));//   
    30.         cf.awaitUninterruptibly();//   
    31.         cf.getSession().write("hello,测试!");//   
    32.         //cf.getSession().write("quit");//   
    33.         cf.getSession().close();  
    34.         cf.getSession().getCloseFuture().awaitUninterruptibly();//   
    35.         connector.dispose();   
    36.   
    37.     }  
    38.   
    39. }  

     

  • 相关阅读:
    假期训练七(hdu-2845 dp,hdu-1846,2188 巴什博奕)
    假期训练六(poj-1753,递归+hdu-2844,多重背包)
    假期训练五(poj-1077bfs+康拓展开,hdu-2577dp)
    1-10假期训练(hdu-2059 简单dp)
    1-9-假期训练心得(dp+bfs)
    如何在IntelliJ Idea中同时启动不同端口的两个实例
    搭建Springboot监控中心报错A attempt was made to call the method reactor.retry.Retry.retryMax(I)Lreactor/ret)
    使用spring中遇到"java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor"问题
    mvc:annotation-driven的前缀 "mvc"未绑定
    使用Idea构建springmvc框架,出现no bean named 'cacheManager' is defined 错误
  • 原文地址:https://www.cnblogs.com/tankaixiong/p/2760432.html
Copyright © 2020-2023  润新知