简体   繁体   中英

Netty 4.0 - Close Channel on Invalid Input

Basically I have the following decoder:

public class Decoder extends ReplayingDecoder<Packet, Void> {

@Override
public Packet decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    short id = in.readUnsignedByte();
    Packet packet = Packet.newInstance(id);
    if (packet == null) {
        throw new IOException("Wasn't prepared to deal with packet 0x" + Integer.toHexString(id));
    }
    packet.read(in);
    return packet;
}

}

It is designed to take input from the stream, read an unsigned byte packet id and then use that byte to construct a decoder, however the issue I have here is shutting down the system on an invalid input (where the IOException is thrown). I have tried using ChannelHandlerContext.close() and ChannelHandlerContext.channel().close() however both of these end up calling the Decoder in a loop and I land up getting stuck.

Please give me some help in gracefully closing this connection.

On a side note it would also be nice to know how to terminate a connection when a read has blocked for more than x milliseconds.

To close inactive connections you could add a ReadTimeoutHandler to your pipeline. The timeout handler will throw a ReadTimeoutException when no data was received within the specified time period. You can handle this exception in the exceptionCaught() method in the same way as you handle the IOException on invalid input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM