Mina--入門

BtWangZhi發表於2017-09-28

1 依賴包

<!-- 日誌支援 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging-api</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <version>1.7.7</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>1.7.7</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.mina</groupId>
            <artifactId>mina-core</artifactId>
            <version>2.0.16</version>
        </dependency>

2 服務端

public class TextMian {
    private static final String HOST_NAME = "127.0.0.1";

    private static final Integer PORT = 7080;

    private static final InetSocketAddress SOCKET_ADDRESS = new InetSocketAddress(
            HOST_NAME, PORT);

    private IoAcceptor acceptor = null;

    public void listener() {
        // 設定編碼過濾器
        try {
            acceptor = new NioSocketAcceptor();
            acceptor.getFilterChain().addLast(
                    "codec",
                    new ProtocolCodecFilter(new TextLineCodecFactory(Charset
                            .forName("UTF-8"),
                            LineDelimiter.WINDOWS.getValue(),
                            LineDelimiter.WINDOWS.getValue())));
            acceptor.getSessionConfig().setReadBufferSize(1024);
            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);// 設定空閒狀態間隔
            acceptor.setHandler(new Myhandler());// 設定資訊處理類
            acceptor.bind(SOCKET_ADDRESS);// 繫結地址
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Server ->" + PORT);
    }

    public static void main(String[] args) {
        new TextMian().listener();
    }
}

處理器

public class Myhandler extends IoHandlerAdapter {

    @Override
    public void exceptionCaught(IoSession session, Throwable cause)
            throws Exception {
        super.exceptionCaught(session, cause);
        System.out.println("exceptionCaught");
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        super.sessionCreated(session);
        System.out.println("sessionCreated");
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
        System.out.println("sessionOpened");
    }

    /**
     * 關閉時執行的方法
     */
    @Override
    public void sessionClosed(IoSession session) throws Exception {
        super.sessionClosed(session);
        System.out.println("sessionClosed");
    }

    /**
     * 空閒狀態時的,間隔執行
     */
    @Override
    public void sessionIdle(IoSession session, IdleStatus status)
            throws Exception {
        super.sessionIdle(session, status);
        System.out.println("sessionIdle");
    }

    /**
     * 有資料傳送時執行
     */
    @SuppressWarnings("deprecation")
    @Override
    public void messageReceived(IoSession session, Object message)
            throws Exception {
        super.messageReceived(session, message);
        System.out.println("messageReceived");
        String msg = (String) message;
        System.out.println("伺服器端接受到的資料為--》" + msg);
        if ("exit".equals(msg)) {
            session.close();
        }
        Date date = new Date();
        session.write(date);
    }
}

3 啟動服務端,然後啟動windows控制檯來模擬客戶端。
連線服務端:
這裡寫圖片描述
傳送訊息:
這裡寫圖片描述

4 Mina客戶端

public class MinaClient {

    private static final String HOST_NAME = "127.0.0.1";

    private static final Integer PORT = 7080;

    private static final InetSocketAddress SOCKET_ADDRESS = new InetSocketAddress(
            HOST_NAME, PORT);

    @SuppressWarnings("deprecation")
    public void listener() {
        IoSession session = null;

        IoConnector connector = new NioSocketConnector();
        connector.setConnectTimeout(3000);
        // 設定過濾器
        connector.getFilterChain().addLast(
                "coderc",
                new ProtocolCodecFilter(new TextLineCodecFactory(Charset
                        .forName("UTF-8"), LineDelimiter.WINDOWS.getValue(),
                        LineDelimiter.WINDOWS.getValue())));
        connector.setHandler(new MyClientHandler());
        ConnectFuture future = connector.connect(SOCKET_ADDRESS);
        future.awaitUninterruptibly();// 等待連線
        session = future.getSession();
        session.write("你好!watchmen");
        session.getCloseFuture().awaitUninterruptibly();// 等待關閉連線
        connector.dispose();
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new MinaClient().listener();
    }
}

public class MyClientHandler extends IoHandlerAdapter {

    @Override
    public void exceptionCaught(IoSession session, Throwable cause)
            throws Exception {
        System.out.println("exceptionCaught");
    }

    @Override
    public void messageReceived(IoSession session, Object message)
            throws Exception {
        String msg = (String) message;
        System.out.println(message);
    }
}

啟動服務端和客戶端,即可看到效果:
這裡寫圖片描述
參考部落格:https://yq.aliyun.com/articles/50581