Mina框架实现最简单的服务端(一)

时间:2021-12-14 20:48:55

创建和启动服务端

package minabase.server;

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.transport.socket.nio.NioSocketAcceptor;

/**
 * Class Description: 用mina框架启动服务端
 * Copyright:   Copyright (c)
 *
 */
public class server
{
    private static IoAcceptor acceptor = null;
    
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        int port = 8100;
        
        try
        {
            String codecName = "US-ASCII";
            
            //创建一个非阻塞的 server 端的 Socket
            acceptor = new NioSocketAcceptor();
            
            //设置读取数据的缓冲区大小
            acceptor.getSessionConfig().setReadBufferSize(2048);
            
            //读写通道10秒内无操作进入空闲状态
            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 120000);
            
            //acceptor.getFilterChain().addLast("logger", new MyLoggingFilter());
            
            acceptor.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new MyCodecFactory(new MyCodecDecoder(
                    Charset.forName(codecName)), new MyCodecEncoder(Charset.forName(codecName)))));
            
            //acceptor.getFilterChain().addLast("session", new SessionFilter());
            
            // 绑定逻辑处理器
            acceptor.setHandler(new BusinessHandler());
            
            //绑定端口
            acceptor.bind(new InetSocketAddress(port));
            
            System.out.println("Server starts successfully ... port: " + port);
        }
        catch (Exception e)
        {
            System.out.println("Server starts unsuccessfully with the xception: " + e);
            if (!acceptor.isDisposed())
            {
                acceptor.dispose();
            }
        }
    }
    
}