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);
}
}
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);
}
}