日期:2014-05-16 浏览次数:20877 次
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); } }