use of com.squareup.okhttp.ws.WebSocket 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());
}
}
});
}
Aggregations