现在,我有以下使用OkHttp与WebSockets配合使用的类,但其设置方式是我无法保持WebSocket处于打开状态,因此可以向Web套接字发送新消息。如何在不创建新的websocket连接的情况下继续向同一打开的websocket发送消息?
public class OkHttp extends WebSocketListener {
public void run() {
String hostname = "127.0.0.1";
int port = 8888;
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(hostname, port));
OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).readTimeout(10, TimeUnit.SECONDS).build();
Request request = new Request.Builder().url("ws://echo.websocket.org").build();
client.newWebSocket(request, this);
// Trigger shutdown of the dispatcher's executor so this process can exit
// cleanly.
client.dispatcher().executorService().shutdown();
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("Hello...");
webSocket.send("...World!");
webSocket.send(ByteString.decodeHex("deadbeef"));
webSocket.close(1000, "Goodbye, World!");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
System.out.println("MESSAGE: " + text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
System.out.println("MESSAGE: " + bytes.hex());
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(1000, null);
System.out.println("CLOSE: " + code + " " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
t.printStackTrace();
}
}
答案 0 :(得分:2)
newWebSocket()
方法返回一个WebSocket
,您可以使用它来排队出站邮件。