Search in sources :

Example 1 with WebSocketListener

use of com.squareup.okhttp.ws.WebSocketListener in project weex-example by KalicyZhou.

the class DefaultWebSocketAdapter method connect.

@Override
public void connect(String url, @Nullable String protocol, EventListener listener) {
    this.eventListener = listener;
    OkHttpClient okHttpClient = new OkHttpClient();
    Request.Builder builder = new Request.Builder();
    if (protocol != null) {
        builder.addHeader(HEADER_SEC_WEBSOCKET_PROTOCOL, protocol);
    }
    builder.url(url);
    WebSocketCall.create(okHttpClient, builder.build()).enqueue(new WebSocketListener() {

        @Override
        public void onOpen(WebSocket webSocket, Request request, Response response) throws IOException {
            ws = webSocket;
            eventListener.onOpen();
        }

        @Override
        public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
            eventListener.onMessage(payload.readUtf8());
            payload.close();
        }

        @Override
        public void onPong(Buffer payload) {
        }

        @Override
        public void onClose(int code, String reason) {
            eventListener.onClose(code, reason, true);
        }

        @Override
        public void onFailure(IOException e) {
            e.printStackTrace();
            if (e instanceof EOFException) {
                eventListener.onClose(WebSocketCloseCodes.CLOSE_NORMAL.getCode(), WebSocketCloseCodes.CLOSE_NORMAL.name(), true);
            } else {
                eventListener.onError(e.getMessage());
            }
        }
    });
}
Also used : Buffer(okio.Buffer) WebSocketListener(com.squareup.okhttp.ws.WebSocketListener) OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request) IOException(java.io.IOException) WebSocket(com.squareup.okhttp.ws.WebSocket) Response(com.squareup.okhttp.Response) EOFException(java.io.EOFException) BufferedSource(okio.BufferedSource)

Aggregations

OkHttpClient (com.squareup.okhttp.OkHttpClient)1 Request (com.squareup.okhttp.Request)1 Response (com.squareup.okhttp.Response)1 WebSocket (com.squareup.okhttp.ws.WebSocket)1 WebSocketListener (com.squareup.okhttp.ws.WebSocketListener)1 EOFException (java.io.EOFException)1 IOException (java.io.IOException)1 Buffer (okio.Buffer)1 BufferedSource (okio.BufferedSource)1