Search in sources :

Example 1 with WebSocketCall

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

the class WXWebSocketManager method connect.

public void connect(String url) {
    try {
        mHttpClient = (OkHttpClient) Class.forName("com.squareup.okhttp.OkHttpClient").newInstance();
    } catch (Exception e) {
        isSupportWebSocket = false;
        return;
    }
    mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
    mHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
    // Disable timeouts for read
    mHttpClient.setReadTimeout(0, TimeUnit.MINUTES);
    Request request = new Request.Builder().url(url).build();
    WebSocketCall call = WebSocketCall.create(mHttpClient, request);
    call.enqueue(this);
}
Also used : WebSocketCall(com.squareup.okhttp.ws.WebSocketCall) Request(com.squareup.okhttp.Request) IOException(java.io.IOException)

Example 2 with WebSocketCall

use of com.squareup.okhttp.ws.WebSocketCall in project incubator-weex by apache.

the class DefaultWebSocketAdapter method connect.

@Override
public void connect(String url, @Nullable final String protocol, EventListener listener) {
    this.eventListener = listener;
    this.wsEventReporter = WSEventReporter.newInstance();
    OkHttpClient okHttpClient = new OkHttpClient();
    Request.Builder builder = new Request.Builder();
    if (protocol != null) {
        builder.addHeader(HEADER_SEC_WEBSOCKET_PROTOCOL, protocol);
    }
    builder.url(url);
    wsEventReporter.created(url);
    Request wsRequest = builder.build();
    WebSocketCall webSocketCall = WebSocketCall.create(okHttpClient, wsRequest);
    try {
        Field field = WebSocketCall.class.getDeclaredField("request");
        field.setAccessible(true);
        Request realRequest = (Request) field.get(webSocketCall);
        Headers wsHeaders = realRequest.headers();
        Map<String, String> headers = new HashMap<>();
        for (String name : wsHeaders.names()) {
            headers.put(name, wsHeaders.values(name).toString());
        }
        wsEventReporter.willSendHandshakeRequest(headers, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    webSocketCall.enqueue(new WebSocketListener() {

        @Override
        public void onOpen(WebSocket webSocket, Request request, Response response) throws IOException {
            ws = webSocket;
            eventListener.onOpen();
            Headers wsHeaders = response.headers();
            Map<String, String> headers = new HashMap<>();
            for (String name : wsHeaders.names()) {
                headers.put(name, wsHeaders.values(name).toString());
            }
            wsEventReporter.handshakeResponseReceived(response.code(), Status.getStatusText(String.valueOf(response.code())), headers);
        }

        @Override
        public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
            if (type == WebSocket.PayloadType.BINARY) {
                wsEventReporter.frameReceived(payload.readByteArray());
            } else {
                String message = payload.readUtf8();
                eventListener.onMessage(message);
                wsEventReporter.frameReceived(message);
            }
            payload.close();
        }

        @Override
        public void onPong(Buffer payload) {
        }

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

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

Example 3 with WebSocketCall

use of com.squareup.okhttp.ws.WebSocketCall in project rskj by rsksmart.

the class Web3WebSocketServerTest method smokeTest.

private void smokeTest(byte[] msg) throws Exception {
    Web3 web3Mock = mock(Web3.class);
    String mockResult = "output";
    when(web3Mock.web3_sha3(anyString())).thenReturn(mockResult);
    int randomPort = 9998;
    TestSystemProperties testSystemProperties = new TestSystemProperties();
    List<ModuleDescription> filteredModules = Collections.singletonList(new ModuleDescription("web3", "1.0", true, Collections.emptyList(), Collections.emptyList()));
    RskWebSocketJsonRpcHandler handler = new RskWebSocketJsonRpcHandler(null);
    JsonRpcWeb3ServerHandler serverHandler = new JsonRpcWeb3ServerHandler(web3Mock, filteredModules);
    int serverWriteTimeoutSeconds = testSystemProperties.rpcWebSocketServerWriteTimeoutSeconds();
    int maxFrameSize = testSystemProperties.rpcWebSocketMaxFrameSize();
    int maxAggregatedFrameSize = testSystemProperties.rpcWebSocketMaxAggregatedFrameSize();
    assertEquals(DEFAULT_WRITE_TIMEOUT_SECONDS, serverWriteTimeoutSeconds);
    assertEquals(DEFAULT_MAX_FRAME_SIZE, maxFrameSize);
    assertEquals(DEFAULT_MAX_AGGREGATED_FRAME_SIZE, maxAggregatedFrameSize);
    Web3WebSocketServer websocketServer = new Web3WebSocketServer(InetAddress.getLoopbackAddress(), randomPort, handler, serverHandler, serverWriteTimeoutSeconds, maxFrameSize, maxAggregatedFrameSize);
    websocketServer.start();
    OkHttpClient wsClient = new OkHttpClient();
    Request wsRequest = new Request.Builder().url("ws://localhost:" + randomPort + "/websocket").build();
    WebSocketCall wsCall = WebSocketCall.create(wsClient, wsRequest);
    CountDownLatch wsAsyncResultLatch = new CountDownLatch(1);
    CountDownLatch wsAsyncCloseLatch = new CountDownLatch(1);
    AtomicReference<Exception> failureReference = new AtomicReference<>();
    wsCall.enqueue(new WebSocketListener() {

        private WebSocket webSocket;

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            wsExecutor.submit(() -> {
                RequestBody body = RequestBody.create(WebSocket.TEXT, msg);
                try {
                    this.webSocket = webSocket;
                    this.webSocket.sendMessage(body);
                    this.webSocket.close(1000, null);
                } catch (IOException e) {
                    failureReference.set(e);
                }
            });
        }

        @Override
        public void onFailure(IOException e, Response response) {
            failureReference.set(e);
        }

        @Override
        public void onMessage(ResponseBody message) throws IOException {
            JsonNode jsonRpcResponse = OBJECT_MAPPER.readTree(message.bytes());
            assertThat(jsonRpcResponse.at("/result").asText(), is(mockResult));
            message.close();
            wsAsyncResultLatch.countDown();
        }

        @Override
        public void onPong(Buffer payload) {
        }

        @Override
        public void onClose(int code, String reason) {
            wsAsyncCloseLatch.countDown();
        }
    });
    if (!wsAsyncResultLatch.await(10, TimeUnit.SECONDS)) {
        fail("Result timed out");
    }
    if (!wsAsyncCloseLatch.await(10, TimeUnit.SECONDS)) {
        fail("Close timed out");
    }
    websocketServer.stop();
    Exception failure = failureReference.get();
    if (failure != null) {
        failure.printStackTrace();
        fail(failure.getMessage());
    }
}
Also used : WebSocketListener(com.squareup.okhttp.ws.WebSocketListener) OkHttpClient(com.squareup.okhttp.OkHttpClient) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) WebSocketCall(com.squareup.okhttp.ws.WebSocketCall) Web3(org.ethereum.rpc.Web3) RequestBody(com.squareup.okhttp.RequestBody) Buffer(okio.Buffer) Request(com.squareup.okhttp.Request) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) WebSocket(com.squareup.okhttp.ws.WebSocket) ResponseBody(com.squareup.okhttp.ResponseBody) Response(com.squareup.okhttp.Response) ModuleDescription(co.rsk.rpc.ModuleDescription) TestSystemProperties(co.rsk.config.TestSystemProperties)

Aggregations

Request (com.squareup.okhttp.Request)3 WebSocketCall (com.squareup.okhttp.ws.WebSocketCall)3 IOException (java.io.IOException)3 OkHttpClient (com.squareup.okhttp.OkHttpClient)2 Response (com.squareup.okhttp.Response)2 WebSocket (com.squareup.okhttp.ws.WebSocket)2 WebSocketListener (com.squareup.okhttp.ws.WebSocketListener)2 Buffer (okio.Buffer)2 TestSystemProperties (co.rsk.config.TestSystemProperties)1 ModuleDescription (co.rsk.rpc.ModuleDescription)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 Headers (com.squareup.okhttp.Headers)1 RequestBody (com.squareup.okhttp.RequestBody)1 ResponseBody (com.squareup.okhttp.ResponseBody)1 EOFException (java.io.EOFException)1 Field (java.lang.reflect.Field)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 CountDownLatch (java.util.concurrent.CountDownLatch)1