All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fastchar.socket.client.tcp.FastTcpSocketClientChannelHandler Maven / Gradle / Ivy

package com.fastchar.socket.client.tcp;

import com.fastchar.socket.core.FastTcpSocket;
import com.fastchar.socket.interfaces.IFastTcpSocketClientListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


public class FastTcpSocketClientChannelHandler  extends SimpleChannelInboundHandler {
    private final IFastTcpSocketClientListener iFastTcpSocketClientListener;
    private FastTcpSocket tcpSocket;

    public FastTcpSocketClientChannelHandler(IFastTcpSocketClientListener iFastTcpSocketClientListener) {
        this.iFastTcpSocketClientListener = iFastTcpSocketClientListener;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        tcpSocket = new FastTcpSocket(ctx.channel());
        if (iFastTcpSocketClientListener != null) {
            iFastTcpSocketClientListener.onOpen(tcpSocket);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        if (iFastTcpSocketClientListener != null) {
            iFastTcpSocketClientListener.onClose(tcpSocket, null, 0);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
        if (iFastTcpSocketClientListener != null) {
            iFastTcpSocketClientListener.onClose(tcpSocket, cause, -1);
        }
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (iFastTcpSocketClientListener != null) {
            iFastTcpSocketClientListener.onMessage(tcpSocket, msg);
        }
    }
}