java 网络通信 mina Hello World(基于mina2.0.9)

  • 服务器端
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;

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

/**
 * Mina主程序
 *
 */
public class ServerMain {

    //定义监听接口
    private static final int PORT = 6488;
    
    public static void main(String[] args) throws IOException{
        //创建服务端监控线程
        IoAcceptor acceptor = new NioSocketAcceptor();
        
        acceptor.getSessionConfig().setReadBufferSize(2048);
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
        
        //设置日志记录
        acceptor.getFilterChain().
        addLast("logger", new LoggingFilter());
        
        //设置编码过滤器
        acceptor.getFilterChain().
        addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
        
        //指定业务逻辑处理器
        acceptor.setHandler(new TimeServerHandler());
        
        //设置端口号
        acceptor.bind(new InetSocketAddress(PORT));
        
        //启动监听线程
        //acceptor.bind();
        
    }
    
}

  • 服务器端处理类
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

/**
 * Mina服务器,handle业务逻辑
 * @author alienware
 *
 */
public class TimeServerHandler extends IoHandlerAdapter {

    /**
     * 当一个新客户端连接后触发此方法
     */
    @Override
    public void sessionCreated(IoSession session){
        //显示客户端的ip和端口
        System.out.println(session.getRemoteAddress());
    }
    
    /**
     * 当接口中其他方法抛出异常未被捕获时触发此方法
     */
    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
    
    /**
     * 当接收到客户端的请求信息后触发此方法
     * 消息接收事件
     */
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        String strMsg = message.toString();
        if(strMsg.trim().equalsIgnoreCase("quit")){
            session.close(true);
            return;
        }
        //返回消息字符串
        session.write("Hi Client");
        //打印客户端传来的消息内容
        System.out.println("Message written : " + strMsg );
    }
    
    /**
     * 当连接空闲时触发此方法
     */
    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        System.out.println("IDLE" + session.getIdleCount(status));
    }
    
}

  • 客户端
import org.apache.mina.core.future.ConnectFuture;
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.NioSocketConnector;

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

/**
 * Mina 客户端
 * @author alienware
 *
 */
public class ClientMain {

    public static void main(String[] args) {
        //创建客户端连接
        NioSocketConnector connnector = new NioSocketConnector();
        
        connnector.getFilterChain().
        addLast("logger", new LoggingFilter());
        
        connnector.getFilterChain().
        addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
        
        //设置连接超时检查时间
        connnector.setConnectTimeoutCheckInterval(30);
        connnector.setHandler(new TimeClientHandler());
        
        //建立连接
        ConnectFuture cf = connnector.connect(new InetSocketAddress("192.168.0.100", 6488));
        
        //等待连接创建完成
        cf.awaitUninterruptibly();
        
        cf.getSession().write("Hi Server!");
        cf.getSession().write("quit");
        
        //等待连接断开并释放连接
        cf.getSession().getCloseFuture().awaitUninterruptibly();
        connnector.dispose();
        
    }
}

  • 客户端处理类
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

public class TimeClientHandler extends IoHandlerAdapter {

    /**
     * 当接收到客户端的请求信息后触发此方法
     */
    public void messageReceived(IoSession session, Object message) throws Exception {
        String content = message.toString();
        System.out.println("client receive a message is :" + content);
    }
    
    /**
     * 当信息已经传送给客户端后触发此方法
     */
    public void messageSent(IoSession session, Object message) throws Exception {
        System.out.println("message - > : " + message);
    }
}

  • mina的编程模式跟netty很像,netty学完再学mina显得很简单

你可能感兴趣的:(java 网络通信 mina Hello World(基于mina2.0.9))