日期:2014-05-16  浏览次数:20886 次

Apache Mina简单实例服务器篇
准备工作,将mina-core-2.0.0-M2.jar,slf4j-nop-1.5.8.jar,log4j-over-slf4j-1.5.8.jar
遇到java.lang.NoClassDefFoundError:org/slf4j/LoggerFactory错误不是加上log4j-over-slf4j-1.5.8.jar和slf4j-nop-1.5.8.jar就完了的,因为这两个包下都没有org.slf4j.LoggerFacotyr这个方法,那么正确的解决方法是什么呢?那就是将slf4j-api-1.5.8.jar导进来就行了
package com.heming.apache.mina.samplesserver;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

/**
 * 自定义的消息处理器,必须实现IoHandlerAdapter类
 * @author 何明
 *
 */
public class SamplMinaServerHandler extends IoHandlerAdapter{

	private int count = 0;
	
	/**
	 * 当一个客户端连接进入时
	 */
	@Override
	public void sessionOpened(IoSession session) throws Exception {

		System.out.println("incoming client: " + session.getRemoteAddress());

	}

	/**
	 * 当一个客户端关闭时
	 */
	@Override
	public void sessionClosed(IoSession session) throws Exception {

		System.out.println(session.getRemoteAddress() + "is Disconnection");

	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		//我们已设定了服务器解析的规则是一行一行读取,这里就可以转为String:
		String str = (String)message;
		
		//Write the received data back to remote perr
		System.out.println("收到客户端发来的消息为" + "  " + str);
		
		//将测试消息会送给客户端
		session.write(str + count);
		
		++count;
		
	}
	
	

	
}
package com.heming.apache.mina.samplesserver;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;



/**
 * 简单Mina Server示例
 * @author 何明
 *
 */
public class MainServer {

	public static void main(String []args)throws Exception{
		
		//创建一个非阻塞的Server端Socket,用NIO
		SocketAcceptor acceptor = new NioSocketAcceptor();
		
		//创建接受数据的过滤器
		DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
	
		//设定这个过滤器将一行一行(/r/n)的读取数据
		chain.addLast("myChain", new ProtocolCodecFilter(new TextLineCodecFactory()));
		
		//设定服务器端的消息处理器:一个SamplMinaServerHandler对象
		acceptor.setHandler(new SamplMinaServerHandler());
		
		//服务器端绑定的端口
		int bindPort = 8899;
		
		//绑定端口,启动服务器
		try {
			acceptor.bind(new InetSocketAddress(bindPort));
		} catch (IOException e) {
		
			e.printStackTrace();
		}
		System.out.println("Mina Server is Listing on:=" + bindPort);
		
	}
	
}


1 楼 haoguobing 2009-12-25  
hi 您好!我在apache官方网上下载的jar包 到了半天报错,能发个完整的给我吗?谢谢!
haogb@cobellink.com