java socket,apache mina框架 demo

工作中遇到一个业务需要用socket协议交互,借此机会学习了一些关于socket的资料,学习了一下apache mina框架,中间挖了很多坑,也埋了很多坑,做个笔记。

此demo实现为异步实现

服务端

MinaServer.java
package com.seer.mina;

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

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

/** * 服务端
 *
 * @author seer
 * @date 2017/11/10 16:01
 */
public class MinaServer {
    public static void main(String[] args) {

        // 创建socket
        IoAcceptor ioAcceptor = new NioSocketAcceptor();

        // 通道在10s内无任何操作进入空闲状态
        ioAcceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

        // 设置缓冲,传输内容需要小于此值
        ioAcceptor.getSessionConfig().setReadBufferSize(10 * 1024 * 1024);


        // 设置编码过滤器(文本文件)
        ioAcceptor.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName(MinaConstants.CHARSET))));

        // 设置监听器
        ioAcceptor.setHandler(new MinaServerHandler());

        // 绑定端口
        try {
            ioAcceptor.bind(new InetSocketAddress(MinaConstants.PORT));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.err.println("Mina服务端启动完成。。。");

    }

}


MinaServerHandler.java
package com.seer.mina;

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;

/**
 * 服务端端监听
 * @author seer
 * @date 2017/11/10 15:57
 */
public class MinaServerHandler extends IoHandlerAdapter {
    private int count = 0;

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        System.err.println("有客户端接入,Address:" + session.getRemoteAddress());
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        count++;
        System.err.println("第" + count + "个 Client登录,Address:" + session.getRemoteAddress());
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        System.err.println("连接关闭,Address:" + session.getRemoteAddress());
        session.closeNow();
    }

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


    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {

        // quit的时候连接关闭
        if (message.toString().trim().equalsIgnoreCase("quit")) {
            session.closeNow();
            return;
        }
        System.out.println("服务端,收到的消息:" + message.toString());
        Date date = new Date();
        session.write(date.toString());
    }

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

}

客户端

MinaClient.java
package com.seer.mina;

import org.apache.commons.lang3.StringUtils;
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.transport.socket.nio.NioSocketConnector;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * 客户端
 *
 * @author seer
 * @date 2017/11/10 16:04
 */
public class MinaClient {

    public static void main(String[] args) throws Exception {
        // 创建socket
        NioSocketConnector nioSocketConnector = new NioSocketConnector();

        // 设置超时(s)
        nioSocketConnector.setConnectTimeoutCheckInterval(15);

        // 设置缓冲,传输内容需要小于此值
        nioSocketConnector.getSessionConfig().setReceiveBufferSize(10 * 1024 * 1024);

        // 设置编码过滤器
        nioSocketConnector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName(MinaConstants.CHARSET))));

        // 设置监听器
        nioSocketConnector.setHandler(new MinaClientHandler());

        // 开始连接
        ConnectFuture connectFuture = nioSocketConnector.connect(new InetSocketAddress(MinaConstants.ADDRESS, MinaConstants.PORT));
        connectFuture.awaitUninterruptibly(); // 连接完了,等着吧
        System.err.println("Mina客户端启动完成。。。");

        // 读取输入内容,发送
        int flag = 0;
        System.out.println("输入要发送的内容:");
        while (flag == 0) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String str = bufferedReader.readLine();
            connectFuture.getSession().write(str);

            if (StringUtils.equals("quit", str)) {
                flag = 1;
            }
        }

        // 关闭连接
        nioSocketConnector.dispose();
        connectFuture.getSession().getCloseFuture().awaitUninterruptibly();
    }

}

socket异步

  // 异步,设置监听器
  nioSocketConnector.setHandler(new MinaClientHandler());
      
  // 同步
  // nioSocketConnector.getSessionConfig().setUseReadOperation(true);

socket同步

  // 异步,设置监听器
  // nioSocketConnector.setHandler(new MinaClientHandler());
      
  // 同步
  nioSocketConnector.getSessionConfig().setUseReadOperation(true);

MinaClientHandler.java
package com.seer.mina;

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

public class MinaClientHandler extends IoHandlerAdapter {
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        // 注意MinaCient中的编码拦截器,如果配置不好,这边的内容无法输出
        System.out.println("返回内容:" + message.toString());
    }
}

你可能感兴趣的:(java socket,apache mina框架 demo)