mina框架客户端与服务端+java+maven

import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.prefixedstring.PrefixedStringCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

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

/**
 * Created by Loftor on 2014/8/15.
 */
public class MinaTimeClient {

    public static void main(String[] args) throws Exception {
        IoConnector connector = new NioSocketConnector();
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new PrefixedStringCodecFactory(Charset.forName("UTF-8"))));
        connector.setHandler(new TimeClientHander());
        IoSession session = null;
        for (; ; ) {
            try {
                ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", 9123));
                future.awaitUninterruptibly();
                session = future.getSession();
                System.out.println("连接成功");
                break;
            } catch (RuntimeIoException e) {
                System.err.println("连接失败");
                e.printStackTrace();
                Thread.sleep(5000);
            }
    }
//        ConnectFuture connectFuture = connector.connect(new InetSocketAddress("127.0.0.1",BaseConfig.PORT));
//        //等待建立连接
//        connectFuture.awaitUninterruptibly();
//        System.out.println("连接成功");
//
//        IoSession session = connectFuture.getSession();

            Scanner sc = new Scanner(System.in);

            boolean quit = false;

            while (!quit) {

                String str = sc.next();
                if (str.equalsIgnoreCase("quit")) {
                    quit = true;
                }
                session.write(str);
            }

            //关闭
            if (session != null) {
                if (session.isConnected()) {
                    session.getCloseFuture().awaitUninterruptibly();
                }
                connector.dispose(true);
            }


        }

}

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

/**
 * Created by Loftor on 2014/8/15.
 */


public class TimeClientHander implements IoHandler {

    @Override
    public void exceptionCaught(IoSession arg0, Throwable arg1)
            throws Exception {
        // TODO Auto-generated method stub
        arg1.printStackTrace();
    }

    @Override
    public void messageReceived(IoSession arg0, Object message) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("client接受信息:"+message.toString());
    }

    @Override
    public void messageSent(IoSession arg0, Object message) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("client发送信息"+message.toString());
    }

    @Override
    public void inputClosed(IoSession ioSession) throws Exception {

    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("client与:"+session.getRemoteAddress().toString()+"断开连接");
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("client与:"+session.getRemoteAddress().toString()+"建立连接");
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        // TODO Auto-generated method stub
        System.out.println( "IDLE " + session.getIdleCount( status ));
    }

    @Override
    public void sessionOpened(IoSession arg0) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("打开连接");
    }

}



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.prefixedstring.PrefixedStringCodecFactory;
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.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * Created by jghkjh on 2016/9/6.
 */
public class MinaTimeServer {

    private static final int PORT = 9123;

    public static void main(String[] args) throws Exception{
        // code will go here next
        IoAcceptor acceptor = new NioSocketAcceptor();//监听传入连接的对象
        acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );//记录所有的信息,比如创建session(会话),接收消息,发送消息,关闭会话等
        acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new PrefixedStringCodecFactory( Charset.forName( "UTF-8" ))));//ProtocolCodecFilter(协议编解码过滤器).这个过滤器用来转换二进制或协议的专用数据到消息对象中, 反之亦然。
                                                                                                                                     // 我们这里使用一个已经存在的TextLine工厂,因为我们这里只处理一些文字消息(你不需要再去写编解码部分)。
        acceptor.setHandler(  new TimeServerHandler() );//创建一个handler来实时处理客户端的连接和请求,这个handler 类必须实现 IoHandler这个接口。
        acceptor.getSessionConfig().setReadBufferSize( 2048 );
        acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
        acceptor.bind( new InetSocketAddress(PORT) );
    }
}


//这个类中一般有exceptionCaught, messageReceived 和 sessionIdle这几个方法。
// exceptionCaught 应该总是在handler 中定义,来处理一些异常情况,否则异常信息将无法捕捉。
//exceptionCaught 方法简单地打印了错误的堆栈跟踪和关闭会话。对于大多数程序,这将是标准的做法,除非处理程序可以从异常状态中恢复。
//messageReceived 方法来处理从客户端接收到的数据,这里是将当前时间返回给客户端,当收到quit时,会话将被关闭,也会返回一个当前时间给客户端。
// 根据所使用的协议编解码器,object 这个参数传递的类型有所不同,以及返回的数据时的session.write(Object) 也不同。
// 如果不指定协议的编解码器,你将收到一个类型为IoBuffer 的对象,返回的数据也要求是IoBuffer。
//sessionIdle 方法将定时调用一次会话,保持空闲状态。通过调用acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );来设定时间间隔。
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import java.util.Date;

/**
 * Created by jghkjh on 2016/9/6.
 */
public class TimeServerHandler extends IoHandlerAdapter
{
    @Override
    public void exceptionCaught(IoSession session, Throwable cause ) throws Exception
    {
        cause.printStackTrace();
    }

    @Override
    public void messageReceived( IoSession session, Object message ) throws Exception
    {
        String str = message.toString();
        if( str.trim().equalsIgnoreCase("quit") ) {
            session.close();
            return;
        }

        Date date = new Date();
        session.write( date.toString() );
        System.out.println("Message written...");
    }

    @Override
    public void sessionIdle( IoSession session, IdleStatus status ) throws Exception
    {
        System.out.println( "IDLE " + session.getIdleCount( status ));
    }
}


pom中加入依赖



  org.apache.mina
  mina-core
  2.0.13


  org.slf4j
  slf4j-log4j12
  1.7.21






你可能感兴趣的:(mina框架客户端与服务端+java+maven)