Apache Mina TCP服务

客户端

package com.cnblogs.javalouvre;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.mina.filter.codec.textline.LineDelimiter.WINDOWS;

public class Client {

    private static final Logger log = LoggerFactory.getLogger(Client.class);

    private static final String HOST = "127.0.0.1";
    private static final int PORT = 5678;

    public static void main(String[] args) {
        final NioSocketConnector connector = new NioSocketConnector();
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(UTF_8, WINDOWS.getValue(), WINDOWS.getValue())));
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.setHandler(new IoHandlerAdapter() {

            @Override
            public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
                log.error("客户端处理消息异常: {}", cause.getMessage());
            }

            @Override
            public void messageReceived(IoSession session, Object message) throws Exception {
                log.info("客户端收到消息:{}", message);
            }

            @Override
            public void messageSent(IoSession session, Object message) throws Exception {
                log.info("客户端发送消息:{}", message);
            }

            @Override
            public void sessionOpened(IoSession session) throws Exception {
                log.info("session已打开");
            }

            @Override
            public void sessionClosed(IoSession session) throws Exception {
                log.info("session已关闭");
            }
        });
        final ConnectFuture future = connector.connect(new InetSocketAddress(HOST, PORT));
        // 阻塞直到和服务端连接成功
        future.awaitUninterruptibly();

        final BufferedReader br = new BufferedReader(new InputStreamReader(System.in, UTF_8));
        try {
            String text;
            while (!(text = br.readLine()).equalsIgnoreCase("quit")) {
                future.getSession().write(text);
            }

            connector.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

服务端

package com.cnblogs.javalouvre;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
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.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.mina.filter.codec.textline.LineDelimiter.WINDOWS;

public class Server {

    private static final Logger log = LoggerFactory.getLogger(Server.class);

    private final static int PORT = 5678;

    public static void main(String[] args) {
        final NioSocketAcceptor acceptor = new NioSocketAcceptor();
        // 编码解码过滤器
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(UTF_8, WINDOWS.getValue(), WINDOWS.getValue())));
        // 日志过滤器
        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        // 获取socket会话配置
        final SocketSessionConfig sessionConfig = acceptor.getSessionConfig();
        // 设置缓存大小
        sessionConfig.setReadBufferSize(1024);
        // 设置读写空闲时间相同,都为10秒
        sessionConfig.setIdleTime(IdleStatus.BOTH_IDLE, 10);
        // 注册处理器
        acceptor.setHandler(new IoHandlerAdapter() {

            @Override
            public void messageReceived(IoSession session, Object message) throws Exception {
                log.info("服务端接收消息:{}", message);

                session.write("COPY THAT.");
            }

        });

        try {
            // 绑定端口
            acceptor.bind(new InetSocketAddress(PORT));
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("端口 {} 启动成功", PORT);
    }

}
posted @ 2022-05-06 15:28  Bruce.Chang.Lee  阅读(4)  评论(0编辑  收藏  举报