kucoin-java-sdk icon indicating copy to clipboard operation
kucoin-java-sdk copied to clipboard

Fix WebSocket SocketTimeoutException adding onFailure on KucoinAPICallback

Open denistorresan opened this issue 3 years ago • 0 comments

While socket running gets the exception below, The socket can work for a maximum of 1 day without any errors:

2022-06-11 13:03:47.876 ERROR 22068 --- [.kucoin.com/...] c.k.s.w.l.KucoinPublicWebsocketListener  : Error on private socket

java.net.SocketTimeoutException: sent ping but didn't receive pong within 30000ms (after 225 successful ping/pongs)
        at okhttp3.internal.ws.RealWebSocket.writePingFrame(RealWebSocket.java:545)
        at okhttp3.internal.ws.RealWebSocket$PingRunnable.run(RealWebSocket.java:529)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539)
        at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
        at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
        at java.base/java.lang.Thread.run(Thread.java:833)

I fixed adding the KucoinAPICallback.onFailure method, that allow to manage a reconnection programmatically, please look in the tests on KucoinPublicWSClientTest and KucoinPrivateWSClientTest for a reference implementation. I also updated the Readme.MD with new code, here an example:

public void onLevel2Data() throws Exception {
        kucoinPublicWSClient.onLevel2Data(new KucoinAPICallback<KucoinEvent<Level2ChangeEvent>>() {

			@Override
			public void onResponse(KucoinEvent<Level2ChangeEvent> response) throws KucoinApiException {
	            event.set(response.getData());
	            kucoinPublicWSClient.unsubscribe(PublicChannelEnum.LEVEL2, "ETH-BTC", "KCS-BTC");
	            gotEvent.countDown();
			}

			@Override
			public void onFailure(Throwable cause) {
				System.out.println("WS connection failed. Reconnecting. cause:" + cause.getMessage());

				//reinitializeWSConnection();	//implement this method
			}
        	
        }, "ETH-BTC", "KCS-BTC");
}

the reinitializeWSConnection() may be something like this:

private static KucoinPublicWSClient kucoinPublicWSClient;

public reinitializeWSConnection() {
        kucoinPublicWSClient = new KucoinClientBuilder().withBaseUrl("https://openapi-sandbox.kucoin.com")
                .buildPublicWSClient();

       onLevel2Data();
}

denistorresan avatar Jun 11 '22 12:06 denistorresan