照着网上的例子,一步一步来,但是结果总是不能运行.今天终于成功了.
我分别使用MINA的两个版本做了实验:0.9和1.0.将我实现的过程及遇到的问题分别介绍一下:
运行环境:winXP,eclipse3.2.1,jdk 1.4.2
一、MINA0.9
引用的包:
mina-0.9.0.jar
slf4j-simple.jar
类文件两个:
ReverseEchoServerHandler.java,用来实现IoHandlerAdapter。
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
public class ReverseEchoServerHandler extends IoHandlerAdapter {
/* (non-Javadoc)
* @see org.apache.mina.common.IoHandlerAdapter#exceptionCaught(org.apache.mina.common.IoSession, java.lang.Throwable)
*/
public void exceptionCaught(IoSession session, Throwable arg1) throws Exception {
session.close();
}
/* (non-Javadoc)
* @see org.apache.mina.common.IoHandlerAdapter#messageReceived(org.apache.mina.common.IoSession, java.lang.Object)
*/
public void messageReceived(IoSession session, Object message) throws Exception {
String m = (String)message;
StringBuffer buf = new StringBuffer();StringBuilder
for(int i = m.length() -1;i>=0;i--){
buf.append(m.charAt(i));
}
session.write(buf.toString());
}
}
ReverseEchoServer.java
import java.nio.charset.Charset;
import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.common.TransportType;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.registry.Service;
import org.apache.mina.registry.ServiceRegistry;
import org.apache.mina.registry.SimpleServiceRegistry;
public class ReverseEchoServer {
public static void main(String[] args) throws Exception{
ServiceRegistry registry = new SimpleServiceRegistry();
Service service = new Service("reverse_echo",TransportType.SOCKET,8081);
DefaultIoFilterChainBuilder chain = new DefaultIoFilterChainBuilder();
chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
chain.addLast("logger", new LoggingFilter());
registry.bind(service,new ReverseEchoServerHandler(), chain);
}
}
刚开始时仅使用了mina-0.9.0.jar包,结果总是报错,原来mina的log使用了slf4j,所以还需要这个包.
运行ReverseEchoServer。
用PuTTY看一下效果吧。
二、mina1.0
MINA的第一个例子终于能运行了__2