Spring2.5+MINA2搭建Socket Server

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

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

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

3、ServerHandler实现类

  1. packagecom.supconit.its.server.handler;
  2. importjava.net.InetSocketAddress;
  3. importjava.util.Collections;
  4. importjava.util.Date;
  5. importjava.util.HashSet;
  6. importjava.util.Set;
  7. importorg.apache.log4j.Logger;
  8. importorg.apache.mina.core.service.IoHandlerAdapter;
  9. importorg.apache.mina.core.session.IdleStatus;
  10. importorg.apache.mina.core.session.IoSession;
  11. publicclassServerHandlerextendsIoHandlerAdapter{
  12. privatefinalintIDLE=300;
  13. //privatefinalLoggerlog=LoggerFactory.getLogger(HandlerTwo.class);
  14. privatefinalLoggerlog=Logger.getLogger(ServerHandler.class.getName());
  15. publicstaticSet<IoSession>sessions=Collections.synchronizedSet(newHashSet<IoSession>());
  16. /**
  17. *
  18. */
  19. publicServerHandler(){
  20. }
  21. @Override
  22. publicvoidexceptionCaught(IoSessionsession,Throwablecause)
  23. throwsException{
  24. session.close();
  25. //log.debug("sessionoccuredexception,socloseit.");
  26. log.debug("sessionoccuredexception,socloseit."+cause.getMessage());
  27. }
  28. @Override
  29. publicvoidsessionCreated(IoSessionsession){
  30. //
  31. log.debug("remoteclient["+session.getRemoteAddress().toString()+"]connected.");
  32. session.write("Welcome");
  33. sessions.add(session);
  34. }
  35. @Override
  36. publicvoidmessageReceived(IoSessionsession,Objectmessage)
  37. throwsException{
  38. Stringstr=message.toString();
  39. log.debug("Messagewritten..."+str);
  40. log.debug("客户端"+((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress()+"连接成功!");
  41. /*if(str.trim().equalsIgnoreCase("quit")){
  42. session.close();//
  43. return;
  44. }*/
  45. //Datedate=newDate();
  46. //session.write(date.toString());//
  47. //session.setAttribute(remoteAddress,message);
  48. session.setAttribute("type",message);
  49. StringremoteAddress=((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress();
  50. session.setAttribute("ip",remoteAddress);
  51. }
  52. @Override
  53. publicvoidsessionClosed(IoSessionsession)throwsException{
  54. log.debug("sessionClosed.");
  55. sessions.remove(session);
  56. }
  57. @Override
  58. publicvoidsessionIdle(IoSessionsession,IdleStatusstatus)
  59. throwsException{
  60. log.debug("sessionidle,sodisconnecting......");
  61. session.close();
  62. log.debug("disconnected.");
  63. }
  64. //
  65. @Override
  66. publicvoidmessageSent(IoSessionsession,Objectmessage)throwsException{
  67. log.debug("messageSent.");
  68. //disconnectanidleclient
  69. //session.close();
  70. }
  71. @Override
  72. publicvoidsessionOpened(IoSessionsession)throwsException{
  73. log.debug("sessionOpened.");
  74. //
  75. session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE,IDLE);
  76. }
  77. }

4、过滤器ServerCodeFactory

  1. packagecom.supconit.its.server.handler;
  2. importjava.nio.charset.Charset;
  3. importorg.apache.mina.core.session.IoSession;
  4. importorg.apache.mina.filter.codec.ProtocolCodecFactory;
  5. importorg.apache.mina.filter.codec.ProtocolDecoder;
  6. importorg.apache.mina.filter.codec.ProtocolEncoder;
  7. importorg.apache.mina.filter.codec.textline.LineDelimiter;
  8. importorg.apache.mina.filter.codec.textline.TextLineDecoder;
  9. importorg.apache.mina.filter.codec.textline.TextLineEncoder;
  10. publicclassServerCodeFactoryimplementsProtocolCodecFactory{
  11. privatefinalTextLineEncoderencoder;
  12. privatefinalTextLineDecoderdecoder;
  13. /*finalstaticcharendchar=0x1a;*/
  14. finalstaticcharendchar=0x0d;
  15. publicServerCodeFactory(){
  16. this(Charset.forName("gb2312"));
  17. }
  18. publicServerCodeFactory(Charsetcharset){
  19. encoder=newTextLineEncoder(charset,LineDelimiter.UNIX);
  20. decoder=newTextLineDecoder(charset,LineDelimiter.AUTO);
  21. }
  22. @Override
  23. publicProtocolDecodergetDecoder(IoSessionsession)throwsException{
  24. //TODOAuto-generatedmethodstub
  25. returndecoder;
  26. }
  27. @Override
  28. publicProtocolEncodergetEncoder(IoSessionsession)throwsException{
  29. //TODOAuto-generatedmethodstub
  30. returnencoder;
  31. }
  32. publicintgetEncoderMaxLineLength(){
  33. returnencoder.getMaxLineLength();
  34. }
  35. publicvoidsetEncoderMaxLineLength(intmaxLineLength){
  36. encoder.setMaxLineLength(maxLineLength);
  37. }
  38. publicintgetDecoderMaxLineLength(){
  39. returndecoder.getMaxLineLength();
  40. }
  41. publicvoidsetDecoderMaxLineLength(intmaxLineLength){
  42. decoder.setMaxLineLength(maxLineLength);
  43. }
  44. }

5、启动spring+mina socket server;

  1. packagecom.supconit.its.server.test;
  2. importorg.springframework.context.support.ClassPathXmlApplicationContext;
  3. publicclassTest{
  4. /**
  5. *@paramargs
  6. */
  7. publicstaticvoidmain(String[]args){
  8. ClassPathXmlApplicationContextct=newClassPathXmlApplicationContext("applicationContext.xml");
  9. }
  10. }

6、客户端测试ClintTest

  1. packagecom.supconit.its.server.test;
  2. importjava.net.InetSocketAddress;
  3. importjava.nio.charset.Charset;
  4. importorg.apache.mina.core.future.ConnectFuture;
  5. importorg.apache.mina.filter.codec.ProtocolCodecFilter;
  6. importorg.apache.mina.filter.codec.textline.TextLineCodecFactory;
  7. importorg.apache.mina.filter.logging.LoggingFilter;
  8. importorg.apache.mina.transport.socket.nio.NioSocketConnector;
  9. importcom.supconit.its.server.handler.ServerHandler;
  10. publicclassClintTest{
  11. /**
  12. *@paramargs
  13. */
  14. publicstaticvoidmain(String[]args){
  15. NioSocketConnectorconnector=newNioSocketConnector();
  16. connector.getFilterChain().addLast("logger",newLoggingFilter());
  17. //connector.getFilterChain().addLast("codec",newProtocolCodecFilter(newTextLineCodecFactory(Charset.forName("GBK"))));//
  18. connector.getFilterChain().addLast("codec",newProtocolCodecFilter(newTextLineCodecFactory()));
  19. connector.setConnectTimeout(1);
  20. connector.setHandler(newServerHandler());//
  21. ConnectFuturecf=connector.connect(
  22. newInetSocketAddress("127.0.0.1",1235));//
  23. cf.awaitUninterruptibly();//
  24. cf.getSession().write("hello,测试!");//
  25. //cf.getSession().write("quit");//
  26. cf.getSession().close();
  27. cf.getSession().getCloseFuture().awaitUninterruptibly();//
  28. connector.dispose();
  29. }
  30. }

你可能感兴趣的:(spring)