Arya
Arya

Reputation: 8995

Okhttp websocket send message to open socket

Right now I have the following class which works with WebSockets using OkHttp, but the way it's setup is that I have no way of keeping the WebSocket open so I can send new messages to the web socket. How can I keep sending messages to the same open websocket without creating a new websocket connection?

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();
    }
}

Upvotes: 1

Views: 4474

Answers (1)

Jesse Wilson
Jesse Wilson

Reputation: 40613

The newWebSocket() method returns a WebSocket that you can use to enqueue outbound messages.

Upvotes: 6

Related Questions