Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting socket timeout on netty channel

Tags:

netty

I have a netty channel and I would like to set a timeout on the underlying socket ( it is set by default to 0 ).

The purpose of the timeout is that the not used channel will be closed if nothing is happening for 15 minutes for instance.

Although I dont see any configuration to do so , and the socket itself is also hidden from me.

Thanks

like image 288
Roman Avatar asked Sep 16 '10 12:09

Roman


People also ask

How do you set a socket timeout?

Java socket timeout Answer: Just set the SO_TIMEOUT on your Java Socket, as shown in the following sample code: String serverName = "localhost"; int port = 8080; // set the socket SO timeout to 10 seconds Socket socket = openSocket(serverName, port); socket.

What is socket timeout?

socket timeout — a maximum time of inactivity between two data packets when exchanging data with a server.

Why is socket timing out?

Socket timeouts can occur when attempting to connect to a remote server, or during communication, especially long-lived ones. They can be caused by any connectivity problem on the network, such as: A network partition preventing the two machines from communicating. The remote machine crashing.


1 Answers

If ReadTimeoutHandler class is used, the time-out can be controlled.

Following is a quotation from Javadoc.

public class MyPipelineFactory implements ChannelPipelineFactory {
    private final Timer timer;
    public MyPipelineFactory(Timer timer) {
        this.timer = timer;
    }

    public ChannelPipeline getPipeline() {
        // An example configuration that implements 30-second read timeout:
        return Channels.pipeline(
            new ReadTimeoutHandler(timer, 30), // timer must be shared.
            new MyHandler());
    }
}


ServerBootstrap bootstrap = ...;
Timer timer = new HashedWheelTimer();
...
bootstrap.setPipelineFactory(new MyPipelineFactory(timer));
...

When it will cause a time-out, MyHandler.exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) is called with ReadTimeoutException.

@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
    if (e.getCause() instanceof ReadTimeoutException) {
        // NOP
    }
    ctx.getChannel().close();
}
like image 102
Yu Sun corn Avatar answered Sep 20 '22 13:09

Yu Sun corn