Mina Server实例

在公司写了个Mina 服务器端的实例,供大家学习参考:

package com.cemso.mina.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

/**
 * @author gl65293
 */
public class MinaTimeServer {

    private static final int PORT = 9123;

    public static void main(String[] args) throws IOException{

        IoAcceptor acceptor = new NioSocketAcceptor();

        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));

        acceptor.setHandler(new TimeServerHandler());
        acceptor.getSessionConfig().setReadBufferSize(2048);
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
        acceptor.bind(new InetSocketAddress(PORT));

    }
}

package com.cemso.mina.server;

/**
 * @author gl65293
 *
 */
import java.util.Date;

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

public class TimeServerHandler extends IoHandlerAdapter {

    public TimeServerHandler() {
    }

    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        cause.printStackTrace();
    }

    public void messageReceived(IoSession session, Object message) throws Exception {
        String str = message.toString();
        if (str.trim().equalsIgnoreCase("quit")) {
            session.close(true);
            return;
        } else {
            Date date = new Date();
            session.write(date.toString());
            System.out.println("Message written...");
            return;
        }
    }

    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        System.out.println((new StringBuilder()).append("IDLE ").append(session.getIdleCount(status)).toString());
    }
}

C:\Documents and Settings\gl65293\Desktop\Mina\examplejars\log4j-1.2.15.jar
C:\Documents and Settings\gl65293\Desktop\Mina\examplejars\mina-core-2.0.4.jar
C:\Documents and Settings\gl65293\Desktop\Mina\examplejars\mina-example-2.0.4.jar
C:\Documents and Settings\gl65293\Desktop\Mina\examplejars\slf4j-api-1.5.11.jar
C:\Documents and Settings\gl65293\Desktop\Mina\examplejars\slf4j-log4j12-1.5.0.jar

你可能感兴趣的:(Mina Server实例)