com.binance.connector.client.utils.WebSocketConnection Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of binance-connector-java Show documentation
Show all versions of binance-connector-java Show documentation
lightweight connector to API
package com.binance.connector.client.utils;
import java.util.concurrent.atomic.AtomicInteger;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WebSocketConnection extends WebSocketListener {
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
private static final int NORMAL_CLOSURE_STATUS = 1000;
private static final OkHttpClient client = HttpClientSingleton.getHttpClient();
private static final Logger logger = LoggerFactory.getLogger(WebSocketConnection.class);
private final WebSocketCallback callback;
private final int connectionId;
private final Request request;
private final String streamName;
private WebSocket webSocket;
private final Object mutex;
public WebSocketConnection(WebSocketCallback callback, Request request) {
this.callback = callback;
this.connectionId = WebSocketConnection.connectionCounter.incrementAndGet();
this.request = request;
this.streamName = request.url().host() + request.url().encodedPath();
this.webSocket = null;
this.mutex = new Object();
}
public void connect() {
synchronized (mutex) {
if (null == webSocket) {
logger.info("[Connection {}] Connecting to {}", connectionId, streamName);
webSocket = client.newWebSocket(request, this);
} else {
logger.info("[Connection {}] is already connected to {}", connectionId, streamName);
}
}
}
public int getConnectionId() {
return connectionId;
}
public void close() {
if (null != webSocket) {
logger.info("[Connection {}] Closing connection to {}", connectionId, streamName);
webSocket.close(NORMAL_CLOSURE_STATUS, null);
}
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
logger.info("[Connection {}] Connected to Server", connectionId);
}
@Override
public void onMessage(WebSocket webSocket, String text) {
callback.onReceive(text);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
logger.error("[Connection {}] Failure", connectionId, t);
}
}