AbstractMatrixIoHandler.java 2.27 KB
package com.example.mina.client.base;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

/**
 * @author dy
 */
@Data
@Slf4j
public abstract class AbstractMatrixIoHandler extends IoHandlerAdapter {

    protected MatrixDataProxy matrixDataProxy;

    public AbstractMatrixIoHandler(MatrixDataProxy matrixDataProxy) {
        this.matrixDataProxy = matrixDataProxy;
    }

    protected MatrixConnectConfig getConnectConfig(IoSession session) {
        Object boxConnectConfig = session.getAttribute(MatrixConstants.SESSION_CONFIG_NAME);

        if( boxConnectConfig instanceof MatrixConnectConfig) {
            return (MatrixConnectConfig) boxConnectConfig;
        }
        return null;
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable throwable) {
    }

    @Override
    public void messageReceived(IoSession session, Object message) {
        if (!(message instanceof IoBuffer)) {
            log.error("客户端接收到的消息不为定义的响应类! message:" + message);
            throw new RuntimeException("Unsupported response message");
        }

        //TODO 客户端将数据服务器的字符串数组读取出来
        byte[] response = null;
        log.info("the client recieved the device response, device:{}, response is: {}",
                getConnectConfig(session), response);
        handleCommandResponse(response);
    }

    @Override
    public void messageSent(IoSession session, Object message) {
    }

    @Override
    public void inputClosed(IoSession session) {
    }

    @Override
    public void sessionClosed(IoSession session) {
    }

    @Override
    public void sessionCreated(IoSession session) {

    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) {
        log.info("the session with box was idle, device is {}", getConnectConfig(session));
    }

    @Override
    public void sessionOpened(IoSession session) {
        log.info("the system has connected to device, device is {}", getConnectConfig(session));
    }

    abstract public boolean handleCommandResponse(byte[] response);
}