MINA学习(二)mina-2.0.0-M3集成spring的示例

本文介绍如何使用Apache Mina 2.0.0-M3版本与Spring框架集成,通过示例展示如何配置服务器端与客户端进行消息交互。包括pom.xml中依赖配置、服务器端实现类MinaProtocolHandler、Spring配置文件applicationContext-mina.xml及客户端测试示例。
摘要由CSDN通过智能技术生成
MINA学习(二)mina-2.0.0-M3集成spring的示例

1.首先导入jar包咯
pom.xml如下:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId>
<version>2.0.0-M3</version>
</dependency>
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-integration-spring</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-integration-beans</artifactId>
<version>2.0.0-M3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.5.2</version>
</dependency>

其中比较麻烦的就是这个slf4j了。版本问题还要注意下,而且版本要和log4j配合,不然有时会报log4j里面的Method not found

2.SERVER端的实现类
只简单的实现了收到client的信息,然后打印出来,然后再回复client一个信息
从MINA下面的例子chat里面整理出来的代码
MinaProtocolHandler.java:

package com.sillycat.api.mina;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MinaProtocolHandler extends IoHandlerAdapter {

private final Logger logger = LoggerFactory.getLogger(getClass());

// private final Set<IoSession> sessions = Collections
// .synchronizedSet(new HashSet<IoSession>());

public void messageReceived(IoSession session, Object message) {
String msg = (String) message;
System.out.println("Server Received: " + msg);
session.write("Server Send: " + msg);
// sessions.add(session);
}

public void sessionIdle(IoSession session, IdleStatus status) {
// disconnect an idle client
session.close();
}

// public void sessionClosed(IoSession session) throws Exception {
// sessions.remove(session);
// }

public void exceptionCaught(IoSession session, Throwable cause) {
logger.warn("Unexpected exception.", cause);
session.close();
}

}

3.spring的配置文件applicationContext-mina.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<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 IoHandler implementation -->
<bean id="minaHandler" class="com.sillycat.api.mina.MinaProtocolHandler"/>
<!-- the IoFilters -->
<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" />
</constructor-arg>
</bean>
<bean id="loggingFilter"
class="org.apache.mina.filter.logging.LoggingFilter" />
<!-- The non-SSL filter chain. -->
<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>
<!-- The IoAcceptor which binds to port 1235 server side -->
<bean id="minaAcceptor"
class="org.apache.mina.transport.socket.nio.NioSocketAcceptor"
init-method="bind" destroy-method="unbind">
<property name="defaultLocalAddress" value=":1235" />
<property name="handler" ref="minaHandler" />
<property name="reuseAddress" value="true" />
<property name="filterChainBuilder" ref="filterChainBuilder" />
</bean>
</beans>

启动TOMCAT,里面spring的Contentloader装载applicationContext-mina.xml,那么就启动了1235这个端口了

就可以telnet localhost 1235来测试了。嘿嘿。

4.Client的测试示例
MinaClientSupport.java:

package com.sillycat.api.mina.client;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.logging.MdcInjectionFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class MinaClientSupport {

private IoHandler handler = null;

private IoSession session;

private String host;

private int port;

public boolean send(Object message) {
if (session != null && session.isConnected()) {
throw new IllegalStateException(
"Already connected. Disconnect first.");
}
SocketAddress address = new InetSocketAddress(host, port);
NioSocketConnector connector = new NioSocketConnector();
try {

connector.getFilterChain().addLast("mdc", new MdcInjectionFilter());

connector.setHandler(handler);
ConnectFuture future1 = connector.connect(address);
future1.awaitUninterruptibly();
if (!future1.isConnected()) {
return false;
}
session = future1.getSession();
session.write(message);
return true;
} catch (Exception e) {
return false;
}
}

public void close(){
if (session != null) {
if (session.isConnected()) {
// Wait until the chat ends.
session.getCloseFuture().awaitUninterruptibly();
}
session.close();
}
}

public String getHost() {
return host;
}

public void setHost(String host) {
this.host = host;
}

public int getPort() {
return port;
}

public void setPort(int port) {
this.port = port;
}

public void setHandler(IoHandler handler) {
this.handler = handler;
}

public static void main(String[] args) {
System.out.println("---------------------");
MinaClientSupport client = new MinaClientSupport();
MinaClientHandler handler = new MinaClientHandler();
client.setHandler(handler);
client.setHost("localhost");
client.setPort(1235);
String msg = "hello world!";
client.send(msg);
System.out.println("Client Send: " + msg);
client.close();
}
}

另外Client端设置一个handler,接收服务端回复过来的信息
MinaClientHandler.java:

package com.sillycat.api.mina.client;

import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;

public class MinaClientHandler extends IoHandlerAdapter {

private static final IoFilter LOGGING_FILTER = new LoggingFilter();

private static final IoFilter CODEC_FILTER = new ProtocolCodecFilter(
new TextLineCodecFactory());

@Override
public void sessionCreated(IoSession session) throws Exception {
session.getFilterChain().addLast("codec", CODEC_FILTER);
session.getFilterChain().addLast("logger", LOGGING_FILTER);
}


@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
String msg = (String) message;
System.out.println("Client Received: " + msg);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值