Spring2.5+MINA2搭建Socket Server
1、下载相应的开发包http://mina.apache.org/,MINA2.0版本包含了spring开发包,还需下载其他相关包,我的工程用到的包如下图:
2、配置spring的applicationContext.xml,配置mina服务;
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
- <!-- mina server -->
- <bean id="serverHandler" class="com.supconit.its.server.handler.ServerHandler" />
- <!-- executorFilter多线程处理 -->
- <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" />-->
- <!-- 处理对象流时候用ObjectSerializationCodecFactory -->
- <!-- <bean class="org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory" /> -->
- <bean class="com.supconit.its.server.handler.ServerCodeFactory" />
- </constructor-arg>
- </bean>
- <bean id="loggingFilter" class="org.apache.mina.filter.logging.LoggingFilter" />
- <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>
- <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>
- <bean id="ioAcceptor" class="org.apache.mina.transport.socket.nio.NioSocketAcceptor" init-method="bind" destroy-method="unbind">
- <property name="defaultLocalAddress" value=":1235" />
- <property name="handler" ref="serverHandler" />
- <property name="filterChainBuilder" ref="filterChainBuilder" />
- <property name="reuseAddress" value="true" />
- </bean>
3、ServerHandler实现类
- package com.supconit.its.server.handler;
- import java.net.InetSocketAddress;
- import java.util.Collections;
- import java.util.Date;
- import java.util.HashSet;
- import java.util.Set;
- import org.apache.log4j.Logger;
- import org.apache.mina.core.service.IoHandlerAdapter;
- import org.apache.mina.core.session.IdleStatus;
- import org.apache.mina.core.session.IoSession;
- public class ServerHandler extends IoHandlerAdapter {
- private final int IDLE = 300;
- //private final Logger log = LoggerFactory .getLogger(HandlerTwo.class);
- private final Logger log = Logger.getLogger(ServerHandler.class.getName());
- public static Set<IoSession> sessions = Collections .synchronizedSet(new HashSet<IoSession>());
- /**
- *
- */
- public ServerHandler(){
- }
- @Override
- public void exceptionCaught(IoSession session, Throwable cause)
- throws Exception {
- session.close();
- //log.debug("session occured exception, so close it.");
- log.debug("session occured exception, so close it." + cause.getMessage());
- }
- @Override
- public void sessionCreated(IoSession session) {
- //
- log.debug("remote client ["+session.getRemoteAddress().toString()+"] connected.");
- session.write("Welcome");
- sessions.add(session);
- }
- @Override
- public void messageReceived(IoSession session, Object message)
- throws Exception {
- String str = message.toString();
- log.debug("Message written..." + str);
- log.debug("客户端"+((InetSocketAddress) session.getRemoteAddress()).getAddress().getHostAddress()+"连接成功!");
- /*if (str.trim().equalsIgnoreCase("quit")) {
- session.close();//
- return;
- }*/
- //Date date = new Date();
- //session.write(date.toString());//
- //session.setAttribute(remoteAddress, message);
- session.setAttribute("type", message);
- String remoteAddress = ((InetSocketAddress) session.getRemoteAddress()).getAddress().getHostAddress();
- session.setAttribute("ip", remoteAddress);
- }
- @Override
- public void sessionClosed(IoSession session) throws Exception {
- log.debug("sessionClosed.");
- sessions.remove(session);
- }
- @Override
- public void sessionIdle(IoSession session, IdleStatus status)
- throws Exception {
- log.debug("session idle, so disconnecting......");
- session.close();
- log.debug("disconnected.");
- }
- //
- @Override
- public void messageSent(IoSession session, Object message) throws Exception {
- log.debug("messageSent.");
- // disconnect an idle client
- //session.close();
- }
- @Override
- public void sessionOpened(IoSession session) throws Exception {
- log.debug("sessionOpened.");
- //
- session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, IDLE);
- }
- }
4、过滤器ServerCodeFactory
- package com.supconit.its.server.handler;
- import java.nio.charset.Charset;
- import org.apache.mina.core.session.IoSession;
- import org.apache.mina.filter.codec.ProtocolCodecFactory;
- import org.apache.mina.filter.codec.ProtocolDecoder;
- import org.apache.mina.filter.codec.ProtocolEncoder;
- import org.apache.mina.filter.codec.textline.LineDelimiter;
- import org.apache.mina.filter.codec.textline.TextLineDecoder;
- import org.apache.mina.filter.codec.textline.TextLineEncoder;
- public class ServerCodeFactory implements ProtocolCodecFactory {
- private final TextLineEncoder encoder;
- private final TextLineDecoder decoder;
- /*final static char endchar = 0x1a;*/
- final static char endchar = 0x0d;
- public ServerCodeFactory() {
- this(Charset.forName("gb2312"));
- }
- public ServerCodeFactory(Charset charset) {
- encoder = new TextLineEncoder(charset, LineDelimiter.UNIX);
- decoder = new TextLineDecoder(charset, LineDelimiter.AUTO);
- }
- @Override
- public ProtocolDecoder getDecoder(IoSession session) throws Exception {
- // TODO Auto-generated method stub
- return decoder;
- }
- @Override
- public ProtocolEncoder getEncoder(IoSession session) throws Exception {
- // TODO Auto-generated method stub
- return encoder;
- }
- public int getEncoderMaxLineLength() {
- return encoder.getMaxLineLength();
- }
- public void setEncoderMaxLineLength(int maxLineLength) {
- encoder.setMaxLineLength(maxLineLength);
- }
- public int getDecoderMaxLineLength() {
- return decoder.getMaxLineLength();
- }
- public void setDecoderMaxLineLength(int maxLineLength) {
- decoder.setMaxLineLength(maxLineLength);
- }
- }
5、启动spring+mina socket server;
- package com.supconit.its.server.test;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class Test {
- /**
- * @param args
- */
- public static void main(String[] args) {
- ClassPathXmlApplicationContext ct = new ClassPathXmlApplicationContext("applicationContext.xml");
- }
- }
6、客户端测试ClintTest
- package com.supconit.its.server.test;
- import java.net.InetSocketAddress;
- import java.nio.charset.Charset;
- import org.apache.mina.core.future.ConnectFuture;
- import org.apache.mina.filter.codec.ProtocolCodecFilter;
- import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
- import org.apache.mina.filter.logging.LoggingFilter;
- import org.apache.mina.transport.socket.nio.NioSocketConnector;
- import com.supconit.its.server.handler.ServerHandler;
- public class ClintTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- NioSocketConnector connector = new NioSocketConnector();
- connector.getFilterChain().addLast( "logger", new LoggingFilter() );
- //connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "GBK" )))); //
- connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( )));
- connector.setConnectTimeout(1);
- connector.setHandler(new ServerHandler());//
- ConnectFuture cf = connector.connect(
- new InetSocketAddress("127.0.0.1", 1235));//
- cf.awaitUninterruptibly();//
- cf.getSession().write("hello,测试!");//
- //cf.getSession().write("quit");//
- cf.getSession().close();
- cf.getSession().getCloseFuture().awaitUninterruptibly();//
- connector.dispose();
- }
- }
转载于:https://www.cnblogs.com/tankaixiong/archive/2012/11/08/2760432.html
Spring2.5+MINA2搭建Socket Server相关推荐
- 从零开始用Python搭建Socket服务器(初篇)
本文假设你学过Python方面的知识 文章目录 前言 Socket 1.基本结构 2.高级应用 前言 如何加密自己的信息?如何基本安全的发送自己的信息? Python的Socket库搭建的服务器可以完 ...
- C# Socket Server 收不到数据
#/usr/bin/env python # -*- coding: utf-8 -*-# C# Socket Server 收不到数据 # 说明: # 最近在调Python通过Socket Clie ...
- 在Windows Server 2012 R2中搭建SQL Server 2012故障转移集群
需要说明的是我们搭建的SQL Server故障转移集群(SQL Server Failover Cluster)是可用性集群,而不是负载均衡集群,其目的是为了保证服务的连续性和可用性,而不是为了提高服 ...
- 面向连接的Socket Server的简单实现
一.基本原理 有时候我们需要实现一个公共的模块,需要对多个其他的模块提供服务,最常用的方式就是实现一个Socket Server,接受客户的请求,并返回给客户结果. 这经常涉及到如果管理多个连接及如何 ...
- [How TO]-在ubuntu20.10上搭建SVN Server
背景: 做为一名嵌入式工程师,工作了八九年,积攒了大量的学习资料,家里备有3个电脑.好几块硬盘,另外还有百度云盘.阿里云盘等.各种零碎的资料.不知如何分类,导致出现了有的资料只出现在某一个硬盘中,或者 ...
- 使用 nc (Netcat) 建立傳送資料的 socket server
原文:http://blog.longwin.com.tw/2012/02/nc-data-send-socket-server-2012/ 於 Debian / Ubuntu Linux 想要透過 ...
- Ubuntu下搭建Janus Server
Ubuntu下搭建Janus Server 目录 Janus简介 下载和编译 Janus 配置和运行janus 视频通话联调测试 1. Janus简介 Janus 是一个开源的,通过 C 语言实现了对 ...
- 搭建Mock Server
搭建Mock Server 1.为什么要搭建mock-server? 为了更好的分工合作,让前端能在不依赖后端环境的情况下进行开发,其中一种手段就是为前端开发者提供一个 web 容器,这个本地环境就是 ...
- 从0开始搭建SQL Server AlwaysOn 第四篇(配置异地机房节点)
从0开始搭建SQL Server AlwaysOn 第四篇(配置异地机房节点) 第一篇 http://www.cnblogs.com/lyhabc/p/4678330.html 第二篇 http:// ...
最新文章
- sar极化想干矩阵_用于PolSAR图像分类的极化卷积网络
- Ubuntu 设置NAT共享网络(命令行方法)
- cacti中监控squid的方法
- 2017级数据结构助教批改方案
- 【转】Node.js最新Web技术栈(2015年5月)
- 华中农业大学第五届程序设计大赛网络同步赛-G
- muduo网络库学习(一)对io复用的封装Poller,面向对象与基于对象
- 二叉树的遍历:先序 中序 后序遍历的递归与非递归实现及层序遍历
- 信息学奥赛一本通 2071:【例2.14】平均分
- Linux中使用sftp的常用命令
- 使用cl编译器,将记事本写的c文件编译成dll和exe 步骤如下(记事本保存成.c)
- spring动态代理(重要至极)
- VS2017安装打包插件
- 支付交易相关接口文档对接
- 贝叶斯(三)先验分布的确定
- Centos 安装python
- 表格识别1-使用python-opencv实现表格识别
- BLDC电机中的死区时间究竟是什么?
- 小米温湿度计接入金桔通用蓝牙网关
- 【pandas drop()和dropna()函数使用详解】