web3j icon indicating copy to clipboard operation
web3j copied to clipboard

[WebSocket - Infura] How to recover from a closed connection

Open gjeanmart opened this issue 8 years ago • 19 comments

I'm currently experimenting a simple program consuming all the events triggered in a contract. My "simplified" code is the following.

Connection

    public Web3j connect(String url) throws IOException {
        Objects.requireNonNull(url, "ethereum.node.url cannot be null");
        
        Web3j web3j;

        //////// WEBSOCKET ///////////////////////////////////
        if(url.startsWith("ws")) { 
            WebSocketService web3jService = new WebSocketService(url, true);
            web3jService.connect();
            web3j = Web3j.build(web3jService);
            
        //////// HTTP ///////////////////////////////////
        } else { 
            web3j = Web3j.build(new HttpService(url));
        }

        if(log.isDebugEnabled()) {
            String clientVersion = web3j.web3ClientVersion().send().getWeb3ClientVersion();
            log.debug("Connected to Ethereum node {} : {}", url, clientVersion);
        }
        return web3j;
    } 

Event consumer

  public Result getEvents(Web3j web3j, String contractAddress) {
       
       EthFilter filter = new EthFilter(
               DefaultBlockParameterName.EARLIEST, 
               DefaultBlockParameterName.LATEST, 
               contractAddress);

       Result result;
               
       Subscription subscription = web3j.ethLogObservable(filter)
           .subscribe(event -> {
                   String eventHash = event.getTopics().get(0);
                   // ...
                   // result.add 
               });
       
       subscription.unsubscribe();

       return result;        
   }

I'm currently trying this program against wss://rinkeby.infura.io/ws and it works "most of the time" But sometimes just after the program started up and the connection established, I can't retrieve the events

rx.exceptions.OnErrorNotImplementedException: Error sending request] with root cause
java.io.IOException: Request with id 1 timed out
	at org.web3j.protocol.websocket.WebSocketService.lambda$setRequestTimeout$0(WebSocketService.java:174) ~[core-3.5.0.jar!/:na]
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_141]
	at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_141]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_141]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) ~[na:1.8.0_141]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_141]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_141]
	at java.lang.Thread.run(Thread.java:748) [na:1.8.0_141]

Or after a certain period of time, I get

2018-09-11 08:48:30.809 DEBUG 13461 --- [nio-9090-exec-7] o.w.protocol.websocket.WebSocketService  : Sending request: {"jsonrpc":"2.0","method":"eth_newFilter","params":[{"topics":[],"fromBlock":"earliest","toBlock":"latest","address":["0x72F26c20a5903fA6E7CD3aCcF94C915632050B12"]}],"id":21}
2018-09-11 08:48:30.958  INFO 13461 --- [ctReadThread-63] o.w.protocol.websocket.WebSocketClient   : Closed WebSocket connection to wss://rinkeby.infura.io/ws, because of reason: ''.Conection closed remotely: true

rx.exceptions.OnErrorNotImplementedException: Error sending request] with root cause

java.io.IOException: Connection was closed
	at org.web3j.protocol.websocket.WebSocketService.lambda$closeOutstandingRequests$5(WebSocketService.java:434) ~[core-3.5.0.jar:na]
	at java.util.concurrent.ConcurrentHashMap$ValuesView.forEach(ConcurrentHashMap.java:4707) ~[na:1.8.0_181]
	at org.web3j.protocol.websocket.WebSocketService.closeOutstandingRequests(WebSocketService.java:433) ~[core-3.5.0.jar:na]
	at org.web3j.protocol.websocket.WebSocketService.onWebSocketClose(WebSocketService.java:428) ~[core-3.5.0.jar:na]
	at org.web3j.protocol.websocket.WebSocketService$1.onClose(WebSocketService.java:123) ~[core-3.5.0.jar:na]
	at org.web3j.protocol.websocket.WebSocketClient.onClose(WebSocketClient.java:42) ~[core-3.5.0.jar:na]
	at org.java_websocket.client.WebSocketClient.onWebsocketClose(WebSocketClient.java:493) ~[Java-WebSocket-1.3.8.jar:na]
	at org.java_websocket.WebSocketImpl.closeConnection(WebSocketImpl.java:504) ~[Java-WebSocket-1.3.8.jar:na]
	at org.java_websocket.WebSocketImpl.closeConnection(WebSocketImpl.java:515) ~[Java-WebSocket-1.3.8.jar:na]
	at org.java_websocket.WebSocketImpl.eot(WebSocketImpl.java:563) ~[Java-WebSocket-1.3.8.jar:na]
	at org.java_websocket.client.WebSocketClient.handleIOException(WebSocketClient.java:772) ~[Java-WebSocket-1.3.8.jar:na]
	at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:393) ~[Java-WebSocket-1.3.8.jar:na]
	at java.lang.Thread.run(Thread.java:748) [na:1.8.0_181]

My question is more about recommendations and best practices to recover from the classic WebSocket issues with Web3j. Is anybody implemented some sort of reconnection mechanism.

Thanks :)

gjeanmart avatar Sep 11 '18 08:09 gjeanmart

With regards to reconnecting, looks to me like WebSocketClients onClose and onError callbacks need to be updated to use the reconnect method provided by Java-Websocket

    @Override
    public void onClose(int code, String reason, boolean remote) {
        log.info("Closed WebSocket connection to {}, because of reason: '{}'."
                + "Conection closed remotely: {}", uri, reason, remote);
       //reconnect if closed remotely or reason is not NORMAL_CLOSURE
        if (remote || code != 1000) {
                 super.reconnect();
        }
        listener.onClose();
    }
    @Override
    public void onError(Exception e) {
        log.error(String.format("WebSocket connection to {} failed with error", uri), e);
        super.reconnect();
        listener.onError(e);
    }

As I side note, I wonder if Infura also supports a keep-alive?

joshorig avatar Sep 11 '18 21:09 joshorig

With regards to reconnecting, looks to me like WebSocketClients onClose and onError callbacks need to be updated to use the reconnect method provided by Java-Websocket

    @Override
    public void onClose(int code, String reason, boolean remote) {
        log.info("Closed WebSocket connection to {}, because of reason: '{}'."
                + "Conection closed remotely: {}", uri, reason, remote);
       //reconnect if closed remotely or reason is not NORMAL_CLOSURE
        if (remote || code != 1000) {
                 super.reconnect();
        }
        listener.onClose();
    }
    @Override
    public void onError(Exception e) {
        log.error(String.format("WebSocket connection to {} failed with error", uri), e);
        super.reconnect();
        listener.onError(e);
    }

As I side note, I wonder if Infura also supports a keep-alive?

Exceptions do not call onClose and onError methods 😭

ybp825 avatar Oct 24 '18 03:10 ybp825

I have the same problem with 4.1.0 version. Initialization of WebSocketService and Web3j is the same as gjeanmart, small change in event consumer (web3j.ethLogObservable(filter) changed to web3j.ethLogFlowable(filter)). Currently i use wss://ropsten.infura.io/ws and it works some time (from 1 hour to 2 days), but then the connection closes and i get the same errors.

How can i recover the connection or change the approach to obtaining the same data?

eugengusev avatar Jan 08 '19 17:01 eugengusev

Same problem as https://github.com/web3j/web3j/issues/703#issuecomment-452376824. In version 4.3.0

upers avatar Jul 21 '19 08:07 upers

I will try to replicate this issue and find a resolution that we could implement in web3j.

AlexandrouR avatar Aug 02 '19 09:08 AlexandrouR

I there any progress on this?

I am having issue with listening events of the contract. There is no logs regarding reconnection but all of a sudden I get logs like below. The application will then continue to run without receiving any contract events. There's definitely an issue with reinstalling filters as it's not the first time I am having this issue. The subscription made with web3.replayPastAndFutureTransactionsFlowable continues to work though.

2019-10-03 18:55:59.550  WARN 6 --- [pool-3-thread-1] org.web3j.protocol.core.filters.Filter   : The filter has not been found. Filter id: 220585224687391003924240137950793775885
2019-10-03 18:55:59.552 ERROR 6 --- [pool-3-thread-1] org.web3j.protocol.core.filters.Filter   : Error sending request

org.web3j.protocol.core.filters.FilterException: Error sending request
	at org.web3j.protocol.core.filters.Filter.throwException(Filter.java:176) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.run(Filter.java:92) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.reinstallFilter(Filter.java:140) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.pollFilter(Filter.java:123) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.lambda$run$0(Filter.java:83) ~[core-4.3.0.jar!/:na]
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_212]
	at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) ~[na:1.8.0_212]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_212]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) ~[na:1.8.0_212]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_212]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_212]
	at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_212]
Caused by: java.io.IOException: Interrupted WebSocket request
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:135) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.Request.send(Request.java:72) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.LogFilter.sendRequest(LogFilter.java:31) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.run(Filter.java:51) ~[core-4.3.0.jar!/:na]
	... 10 common frames omitted
Caused by: java.lang.InterruptedException: null
	at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:347) ~[na:1.8.0_212]
	at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895) ~[na:1.8.0_212]
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:132) ~[core-4.3.0.jar!/:na]
	... 13 common frames omitted

2019-10-03 18:55:59.589  WARN 6 --- [pool-3-thread-1] org.web3j.protocol.core.filters.Filter   : The filter has not been found. Filter id: 57623030146647081109105239144243991658
2019-10-03 18:55:59.592 ERROR 6 --- [pool-3-thread-1] org.web3j.protocol.core.filters.Filter   : Error sending request

org.web3j.protocol.core.filters.FilterException: Error sending request
	at org.web3j.protocol.core.filters.Filter.throwException(Filter.java:176) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.run(Filter.java:92) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.reinstallFilter(Filter.java:140) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.pollFilter(Filter.java:123) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.lambda$run$0(Filter.java:83) ~[core-4.3.0.jar!/:na]
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_212]
	at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) ~[na:1.8.0_212]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_212]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) ~[na:1.8.0_212]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_212]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_212]
	at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_212]
Caused by: java.io.IOException: Interrupted WebSocket request
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:135) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.Request.send(Request.java:72) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.LogFilter.sendRequest(LogFilter.java:31) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.run(Filter.java:51) ~[core-4.3.0.jar!/:na]
	... 10 common frames omitted
Caused by: java.lang.InterruptedException: null
	at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:347) ~[na:1.8.0_212]
	at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895) ~[na:1.8.0_212]
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:132) ~[core-4.3.0.jar!/:na]
	... 13 common frames omitted

2019-10-03 18:55:59.593  WARN 6 --- [pool-3-thread-1] org.web3j.protocol.core.filters.Filter   : The filter has not been found. Filter id: 203826903671564243051198112765424069178
2019-10-03 18:55:59.594 ERROR 6 --- [pool-3-thread-1] org.web3j.protocol.core.filters.Filter   : Error sending request

org.web3j.protocol.core.filters.FilterException: Error sending request
	at org.web3j.protocol.core.filters.Filter.throwException(Filter.java:176) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.run(Filter.java:92) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.reinstallFilter(Filter.java:140) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.pollFilter(Filter.java:123) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.lambda$run$0(Filter.java:83) ~[core-4.3.0.jar!/:na]
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_212]
	at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) ~[na:1.8.0_212]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_212]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) ~[na:1.8.0_212]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_212]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_212]
	at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_212]
Caused by: java.io.IOException: Interrupted WebSocket request
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:135) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.Request.send(Request.java:72) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.LogFilter.sendRequest(LogFilter.java:31) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.run(Filter.java:51) ~[core-4.3.0.jar!/:na]
	... 10 common frames omitted
Caused by: java.lang.InterruptedException: null
	at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:347) ~[na:1.8.0_212]
	at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895) ~[na:1.8.0_212]
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:132) ~[core-4.3.0.jar!/:na]
	... 13 common frames omitted

2019-10-03 18:55:59.595  WARN 6 --- [pool-3-thread-1] org.web3j.protocol.core.filters.Filter   : The filter has not been found. Filter id: 176436537926014854303587920301394678113
2019-10-03 18:55:59.596 ERROR 6 --- [pool-3-thread-1] org.web3j.protocol.core.filters.Filter   : Error sending request

org.web3j.protocol.core.filters.FilterException: Error sending request
	at org.web3j.protocol.core.filters.Filter.throwException(Filter.java:176) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.run(Filter.java:92) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.reinstallFilter(Filter.java:140) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.pollFilter(Filter.java:123) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.lambda$run$0(Filter.java:83) ~[core-4.3.0.jar!/:na]
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_212]
	at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) ~[na:1.8.0_212]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_212]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) ~[na:1.8.0_212]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_212]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_212]
	at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_212]
Caused by: java.io.IOException: Interrupted WebSocket request
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:135) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.Request.send(Request.java:72) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.LogFilter.sendRequest(LogFilter.java:31) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.run(Filter.java:51) ~[core-4.3.0.jar!/:na]
	... 10 common frames omitted
Caused by: java.lang.InterruptedException: null
	at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:347) ~[na:1.8.0_212]
	at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895) ~[na:1.8.0_212]
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:132) ~[core-4.3.0.jar!/:na]
	... 13 common frames omitted

2019-10-03 18:55:59.596  WARN 6 --- [pool-3-thread-1] org.web3j.protocol.core.filters.Filter   : The filter has not been found. Filter id: 115381160976602894507492994513836193864
2019-10-03 18:55:59.600 ERROR 6 --- [pool-3-thread-1] org.web3j.protocol.core.filters.Filter   : Error sending request

org.web3j.protocol.core.filters.FilterException: Error sending request
	at org.web3j.protocol.core.filters.Filter.throwException(Filter.java:176) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.run(Filter.java:92) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.reinstallFilter(Filter.java:140) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.pollFilter(Filter.java:123) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.lambda$run$0(Filter.java:83) ~[core-4.3.0.jar!/:na]
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_212]
	at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) ~[na:1.8.0_212]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_212]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) ~[na:1.8.0_212]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_212]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_212]
	at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_212]
Caused by: java.io.IOException: Interrupted WebSocket request
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:135) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.Request.send(Request.java:72) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.LogFilter.sendRequest(LogFilter.java:31) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.run(Filter.java:51) ~[core-4.3.0.jar!/:na]
	... 10 common frames omitted
Caused by: java.lang.InterruptedException: null
	at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:347) ~[na:1.8.0_212]
	at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895) ~[na:1.8.0_212]
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:132) ~[core-4.3.0.jar!/:na]
	... 13 common frames omitted

2019-10-03 18:55:59.601  WARN 6 --- [pool-3-thread-1] org.web3j.protocol.core.filters.Filter   : The filter has not been found. Filter id: 299485251384547355900876793292729361227
2019-10-03 18:55:59.601 ERROR 6 --- [pool-3-thread-1] org.web3j.protocol.core.filters.Filter   : Error sending request

org.web3j.protocol.core.filters.FilterException: Error sending request
	at org.web3j.protocol.core.filters.Filter.throwException(Filter.java:176) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.run(Filter.java:92) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.reinstallFilter(Filter.java:140) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.pollFilter(Filter.java:123) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.lambda$run$0(Filter.java:83) ~[core-4.3.0.jar!/:na]
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_212]
	at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) ~[na:1.8.0_212]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_212]
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) ~[na:1.8.0_212]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_212]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_212]
	at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_212]
Caused by: java.io.IOException: Interrupted WebSocket request
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:135) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.Request.send(Request.java:72) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.LogFilter.sendRequest(LogFilter.java:31) ~[core-4.3.0.jar!/:na]
	at org.web3j.protocol.core.filters.Filter.run(Filter.java:51) ~[core-4.3.0.jar!/:na]
	... 10 common frames omitted
Caused by: java.lang.InterruptedException: null
	at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:347) ~[na:1.8.0_212]
	at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895) ~[na:1.8.0_212]
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:132) ~[core-4.3.0.jar!/:na]
	... 13 common frames omitted

mesudip avatar Oct 14 '19 08:10 mesudip

Disposable subscription = web3j.blockFlowable(false).subscribe(block -> {
            try {
                log.info("Sweet, block number " + block.getBlock().getNumber()
                        + " has just been created");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

Add a try catch like the example above.

AlexandrouR avatar Oct 21 '19 14:10 AlexandrouR

In our besu 1.3.5 network , that includes websockets served via AWS ALB + besu, we are receiving similar errors. Just us suggestion, Isnt it worth to use Okhttp for websockets too?

sed by: java.io.IOException: Request with id 4131851 timed out at org.web3j.protocol.websocket.WebSocketService.lambda$setRequestTimeout$0(WebSocketService.java:182) ~[core-4.5.0.jar!/:na] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_232] at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_232] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_232] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) ~[na:1.8.0_232] ... 3 common frames omitted 2019-11-23 20:45:41.546 [EVENT-3] ERROR net.consensys.eventeum.service.DefaultSubscriptionService: triggerListener - An error occurred when processing contractEvent with id 0x645960871453a33122210cf269cfd957 828a659af1ee132c92b892f4c7d10d6c-0xec57dbe9e1174535b825da916726eae19a7388f79feaff7c49b50a0bf70d4303-0 net.consensys.eventeum.chain.service.BlockchainException: Error when obtaining the current block number at net.consensys.eventeum.chain.service.Web3jService.getCurrentBlockNumber(Web3jService.java:201) ~[eventeum-core-1.0.28-SNAPSHOT.jar!/:1.0.28-SNAPSHOT] at net.consensys.eventeum.chain.contract.ConfirmationCheckInitialiser.onEvent(ConfirmationCheckInitialiser.java:44) ~[eventeum-core-1.0.28-SNAPSHOT.jar!/:1.0.28-SNAPSHOT] at net.consensys.eventeum.service.DefaultSubscriptionService.triggerListener(DefaultSubscriptionService.java:238) [eventeum-core-1.0.28-SNAPSHOT.jar!/:1.0.28-SNAPSHOT] at net.consensys.eventeum.service.DefaultSubscriptionService.lambda$null$8(DefaultSubscriptionService.java:226) [eventeum-core-1.0.28-SNAPSHOT.jar!/:1.0.28-SNAPSHOT] at java.util.ArrayList.forEach(ArrayList.java:1257) ~[na:1.8.0_232] at net.consensys.eventeum.service.DefaultSubscriptionService.lambda$registerContractEventFilter$9(DefaultSubscriptionService.java:225) [eventeum-core-1.0.28-SNAPSHOT.jar!/:1.0.28-SNAPSHOT] at net.consensys.eventeum.chain.service.Web3jService.lambda$null$0(Web3jService.java:119) ~[eventeum-core-1.0.28-SNAPSHOT.jar!/:1.0.28-SNAPSHOT] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_232] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_232] at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_232] Caused by: java.io.IOException: Request with id 4131852 timed out at org.web3j.protocol.websocket.WebSocketService.lambda$setRequestTimeout$0(WebSocketService.java:182) ~[core-4.5.0.jar!/:na] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_232] at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_232] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_232] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) ~[na:1.8.0_232]

Ferparishuertas avatar Nov 23 '19 22:11 Ferparishuertas

Anyone has a solution or workaround for that issue?

rwenig026 avatar Dec 30 '19 15:12 rwenig026

Currently I am using a workaround by extending WebSocketClient https://gist.github.com/mesudip/94d49905375cba57950d69c119c97d4b.

If you want to experiment with the issue :

  • setup a geth or parity node
  • setup a reverse proxy like nginx to connect to your ethereum node. Note: You can even setup nginx locally and proxy from localhost to infura node.
  • start your application and connect to node through nginx.
  • shutdown your reverse proxy and restart it.

mesudip avatar Apr 03 '20 06:04 mesudip

same on 4.8.1, Infura mainnet

org.java_websocket.exceptions.WebsocketNotConnectedException: null
	at org.java_websocket.WebSocketImpl.send(WebSocketImpl.java:608)
	at org.java_websocket.WebSocketImpl.send(WebSocketImpl.java:585)
	at org.java_websocket.client.WebSocketClient.send(WebSocketClient.java:309)
	at org.web3j.protocol.websocket.WebSocketService.sendRequest(WebSocketService.java:235)
	at org.web3j.protocol.websocket.WebSocketService.sendAsync(WebSocketService.java:186)
	at org.web3j.protocol.websocket.WebSocketService.send(WebSocketService.java:165)
	at org.web3j.protocol.core.Request.send(Request.java:87)

mmaryo avatar Nov 26 '20 08:11 mmaryo

could you updade Java-WebSocket version ? I see javaWebSocketVersion = '1.3.8' And last release is 1.5.1 since May https://github.com/TooTallNate/Java-WebSocket/releases

mmaryo avatar Nov 26 '20 08:11 mmaryo

There are problems concerning feature org.web3j.protocol.core.filters.Filter.reinstallFilter():

  • it is not possible to tune new filter (we already do not want to listen from previous block number)
  • it does not work because this method is called in scheduled thread and calls schedule.cancel(true);
  • if reinstallation fails (I have this due to strange InterruptedIOException: interrupted at okio.Timeout.throwIfReached) rxjava doOnError() callback does not called

Checked in v4.7.0 but seems like current v4.8.4 code have the same problems.

dofs197 avatar Mar 05 '21 08:03 dofs197

is there any known workaround for the problem? The problem which I am facing is the doOnError callback is never invoked. So, as a client I can't do anything about it.

ffarhanaamin avatar Mar 24 '21 23:03 ffarhanaamin

Currently I am using a workaround by extending WebSocketClient https://gist.github.com/mesudip/94d49905375cba57950d69c119c97d4b.

If you want to experiment with the issue :

  • setup a geth or parity node
  • setup a reverse proxy like nginx to connect to your ethereum node. Note: You can even setup nginx locally and proxy from localhost to infura node.
  • start your application and connect to node through nginx.
  • shutdown your reverse proxy and restart it.

Worked for me. No testing in depth, but after infura issues now running smooth for the last day. If any opposite experiences, i'd report.

BarBozz avatar May 19 '21 19:05 BarBozz

I'm sometimes getting this 'The connection was closed because the other endpoint did not respond with a pong in time. For more information check: https://github.com/TooTallNate/Java-WebSocket/wiki/Lost-connection-detection And after that reconnect fails with error SSLException: Socket closed. I'm using wrapper from @BarBozz . Can someone help me, I'm not very experienced with this.

kobayashimaru871 avatar Aug 18 '21 10:08 kobayashimaru871

Same problem in 4.8.4

java.net.SocketTimeoutException: timeout
	at okio.SocketAsyncTimeout.newTimeoutException(JvmOkio.kt:143)
	at okio.AsyncTimeout.access$newTimeoutException(AsyncTimeout.kt:162)
	at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:335)
	at okio.RealBufferedSource.indexOf(RealBufferedSource.kt:427)
	at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.kt:320)
	at okhttp3.internal.http1.HeadersReader.readLine(HeadersReader.kt:29)
	at okhttp3.internal.http1.Http1ExchangeCodec.readResponseHeaders(Http1ExchangeCodec.kt:178)
	at okhttp3.internal.connection.Exchange.readResponseHeaders(Exchange.kt:106)
	at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.kt:79)
	at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
	at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:34)
	at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
	at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:95)
	at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
	at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
	at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
	at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
	at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
	at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
	at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)
	at org.web3j.protocol.http.HttpService.performIO(HttpService.java:161)
	at org.web3j.protocol.Service.send(Service.java:48)
	at org.web3j.protocol.core.Request.send(Request.java:87)
	at org.web3j.protocol.core.RemoteCall.send(RemoteCall.java:42)
	at io.reactivex.internal.operators.flowable.FlowableFromCallable.call(FlowableFromCallable.java:55)
	at io.reactivex.internal.operators.flowable.FlowableFlatMap$MergeSubscriber.onNext(FlowableFlatMap.java:143)
	at io.reactivex.internal.operators.flowable.FlowableCreate$BufferAsyncEmitter.drain(FlowableCreate.java:547)
	at io.reactivex.internal.operators.flowable.FlowableCreate$BufferAsyncEmitter.onNext(FlowableCreate.java:471)
	at org.web3j.protocol.core.filters.BlockFilter.process(BlockFilter.java:42)
	at org.web3j.protocol.core.filters.Filter.pollFilter(Filter.java:144)
	at org.web3j.protocol.core.filters.Filter.lambda$run$0(Filter.java:92)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
	at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketException: Socket closed
	at java.net.SocketInputStream.read(SocketInputStream.java:204)
	at java.net.SocketInputStream.read(SocketInputStream.java:141)
	at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
	at sun.security.ssl.InputRecord.read(InputRecord.java:503)
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:975)
	at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:933)
	at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
	at okio.InputStreamSource.read(JvmOkio.kt:90)
	at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:129)
	... 35 more

mykola1731 avatar Sep 14 '21 14:09 mykola1731

This was fixed here https://github.com/web3j/web3j/pull/1507, if any issue related to this one occurs please reopen.

AlexandrouR avatar Oct 04 '21 13:10 AlexandrouR

Hello, I am having the same issue as in the original post and can't figure out how to implement the solutions or workarounds. Can somebody please provide an example code of how it works? I am very new to Java in general.

I am facing the following issue specifically: I am struggling for a while now to establish a websococket subscription to an Infura Ethereum Node with Java and particularly Web3j. I am interested in receiving the time stamp of when a new block has been created, which I currently achieve in the following way:

`public class WebSocketTestDiscordQuestion {

//Here I paste my websocket address
static final String INFURA_WS = "wss://my infura websocket address";

public static void main(String[] args) throws URISyntaxException, ConnectException {

    URI uri = new URI(INFURA_WS);
    CustomWebSocketClient webSocketClient = new CustomWebSocketClient(uri);
    WebSocketService web3jService = new WebSocketService(webSocketClient, true);
    web3jService.connect();
    Web3j web3j = Web3j.build(web3jService);

    web3j.blockFlowable(false)
            .subscribe(ethBlock -> {
                        EthBlock.Block block = ethBlock.getBlock();
                        LocalDateTime timestampNode = Instant.ofEpochSecond(
                                        block.getTimestamp()
                                                .longValueExact())
                                .atZone(ZoneId.of("UTC"))
                                .toLocalDateTime();


                        System.out.println(block.getNumber());
                        System.out.println(timestampNode);
                    }
                    , e -> {
                        System.out.println("It broke.");
                    }
            );
}

} `

My issue is that it eventually stops working after a few hours, while I wish to keep it open indefinitely. Is there someone who can help me or point me to an example of how to reconnect and reestablish subscription if it breaks, or another implementation of how to keep receiving the information in perpetuity?

peterdeenichin avatar Nov 05 '22 11:11 peterdeenichin