我正在尝试使用TooTallNate的Java-Websocket库创建一个websocket客户端,以从coinbase交易所websocket流接收消息。由于Python中存在并行化瓶颈,并且据我所知,我在Java中做的事情与Python中相同,因此我正在将自己编写的程序从Python移植到Java。以下是我在Python中使用此websocket库打开连接的代码(这按预期工作):
ws = websocket.create_connection("wss://ws-feed.exchange.coinbase.com", 20)
ws.send(json.dumps({
"type": "subscribe",
"product_id": "BTC-USD"
}))
这是我的整个Java类:
public class CoinbaseWebsocketClient extends WebSocketClient {
private final Gson gson = new Gson();
private CoinbaseWebsocketClient(URI serverURI) {
super(serverURI, new Draft_17());
connect();
}
private static URI uri;
private static CoinbaseWebsocketClient coinbaseWebsocketClient;
static {
try {
uri = new URI("wss://ws-feed.exchange.coinbase.com");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
protected static CoinbaseWebsocketClient get() {
if (coinbaseWebsocketClient == null) {
coinbaseWebsocketClient = new CoinbaseWebsocketClient(uri);
}
return coinbaseWebsocketClient;
}
@Override
public void onOpen(ServerHandshake serverHandshake) {
System.out.println("Websocket open");
final JsonObject btcUSD_Request = new JsonObject();
btcUSD_Request.addProperty("type", "subscribe");
btcUSD_Request.addProperty("product_id", "BTC_USD");
final String requestString = gson.toJson(btcUSD_Request);
send(requestString);
}
@Override
public void onMessage(String s) {
System.out.println("Message received: " + s);
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("Websocket closed: " + reason);
}
@Override
public void onError(Exception e) {
System.err.println("an error occurred:" + e);
}
}
我知道我的Java代码没有根本性的问题,因为当我使用ws://echo.websocket.org作为URI时,它按预期工作。然而,当我尝试连接到wss://ws-feed.exchange.coinbase.com时,我会收到以下错误:
Websocket closed: draft org.java_websocket.drafts.Draft_17@7ca2fefb refuses handshake
据我所知,这个连接没有任何身份验证或类似的东西(我在我的Python程序中没有提供任何身份验证),所以我不知道这个错误的来源。