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

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

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

3、ServerHandler实现类

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

4、过滤器ServerCodeFactory

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

5、启动spring+mina socket server;

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

6、客户端测试ClintTest

 
  1. package com.supconit.its.server.test;
  2. import java.net.InetSocketAddress;
  3. import java.nio.charset.Charset;
  4. import org.apache.mina.core.future.ConnectFuture;
  5. import org.apache.mina.filter.codec.ProtocolCodecFilter;
  6. import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
  7. import org.apache.mina.filter.logging.LoggingFilter;
  8. import org.apache.mina.transport.socket.nio.NioSocketConnector;
  9. import com.supconit.its.server.handler.ServerHandler;
  10. public class ClintTest {
  11. /**
  12. * @param args
  13. */
  14. public static void main(String[] args) {
  15. NioSocketConnector connector = new NioSocketConnector();
  16. connector.getFilterChain().addLast( "logger", new LoggingFilter() );
  17. //connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "GBK" )))); //
  18. connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( )));
  19. connector.setConnectTimeout(1);
  20. connector.setHandler(new ServerHandler());//
  21. ConnectFuture cf = connector.connect(
  22. new InetSocketAddress("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. }

转载于:https://www.cnblogs.com/tankaixiong/archive/2012/11/08/2760432.html

Spring2.5+MINA2搭建Socket Server相关推荐

  1. 从零开始用Python搭建Socket服务器(初篇)

    本文假设你学过Python方面的知识 文章目录 前言 Socket 1.基本结构 2.高级应用 前言 如何加密自己的信息?如何基本安全的发送自己的信息? Python的Socket库搭建的服务器可以完 ...

  2. C# Socket Server 收不到数据

    #/usr/bin/env python # -*- coding: utf-8 -*-# C# Socket Server 收不到数据 # 说明: # 最近在调Python通过Socket Clie ...

  3. 在Windows Server 2012 R2中搭建SQL Server 2012故障转移集群

    需要说明的是我们搭建的SQL Server故障转移集群(SQL Server Failover Cluster)是可用性集群,而不是负载均衡集群,其目的是为了保证服务的连续性和可用性,而不是为了提高服 ...

  4. 面向连接的Socket Server的简单实现

    一.基本原理 有时候我们需要实现一个公共的模块,需要对多个其他的模块提供服务,最常用的方式就是实现一个Socket Server,接受客户的请求,并返回给客户结果. 这经常涉及到如果管理多个连接及如何 ...

  5. [How TO]-在ubuntu20.10上搭建SVN Server

    背景: 做为一名嵌入式工程师,工作了八九年,积攒了大量的学习资料,家里备有3个电脑.好几块硬盘,另外还有百度云盘.阿里云盘等.各种零碎的资料.不知如何分类,导致出现了有的资料只出现在某一个硬盘中,或者 ...

  6. 使用 nc (Netcat) 建立傳送資料的 socket server

    原文:http://blog.longwin.com.tw/2012/02/nc-data-send-socket-server-2012/ 於 Debian / Ubuntu Linux 想要透過 ...

  7. Ubuntu下搭建Janus Server

    Ubuntu下搭建Janus Server 目录 Janus简介 下载和编译 Janus 配置和运行janus 视频通话联调测试 1. Janus简介 Janus 是一个开源的,通过 C 语言实现了对 ...

  8. 搭建Mock Server

    搭建Mock Server 1.为什么要搭建mock-server? 为了更好的分工合作,让前端能在不依赖后端环境的情况下进行开发,其中一种手段就是为前端开发者提供一个 web 容器,这个本地环境就是 ...

  9. 从0开始搭建SQL Server AlwaysOn 第四篇(配置异地机房节点)

    从0开始搭建SQL Server AlwaysOn 第四篇(配置异地机房节点) 第一篇 http://www.cnblogs.com/lyhabc/p/4678330.html 第二篇 http:// ...

最新文章

  1. sar极化想干矩阵_用于PolSAR图像分类的极化卷积网络
  2. Ubuntu 设置NAT共享网络(命令行方法)
  3. cacti中监控squid的方法
  4. 2017级数据结构助教批改方案
  5. 【转】Node.js最新Web技术栈(2015年5月)
  6. 华中农业大学第五届程序设计大赛网络同步赛-G
  7. muduo网络库学习(一)对io复用的封装Poller,面向对象与基于对象
  8. 二叉树的遍历:先序 中序 后序遍历的递归与非递归实现及层序遍历
  9. 信息学奥赛一本通 2071:【例2.14】平均分
  10. Linux中使用sftp的常用命令
  11. 使用cl编译器,将记事本写的c文件编译成dll和exe 步骤如下(记事本保存成.c)
  12. spring动态代理(重要至极)
  13. VS2017安装打包插件
  14. 支付交易相关接口文档对接
  15. 贝叶斯(三)先验分布的确定
  16. Centos 安装python
  17. 表格识别1-使用python-opencv实现表格识别
  18. BLDC电机中的死区时间究竟是什么?
  19. 小米温湿度计接入金桔通用蓝牙网关
  20. 【pandas drop()和dropna()函数使用详解】

热门文章

  1. 深度丨如何理解和评价机器学习中的表达能力、训练难度和泛化性能
  2. 费曼:所有的科学知识都是不确定的
  3. 人工智能应用实践与趋势
  4. 图解全球无人驾驶产业链:这些公司在主宰人类出行的未来
  5. 如果编程语言是飞机 | 每日趣闻
  6. 如何在 7 天内写一个程序? | 每日趣闻
  7. 大厂围城:千辛万苦杀进来,为何他们选择出逃?
  8. 新年福利 | “社区之星”(社区核心贡献者)成长故事征集
  9. 学完 CompletionService,可以做时间管理大师?
  10. 阿里巴巴JAVA面试真题(三)