Search in sources :

Example 41 with WebSocket

use of okhttp3.WebSocket in project apollo-android by apollographql.

the class WebSocketSubscriptionTransport method send.

@Override
public void send(OperationClientMessage message) {
    WebSocket socket = webSocket.get();
    if (socket == null) {
        throw new IllegalStateException("Not connected");
    }
    socket.send(message.toJsonString());
}
Also used : WebSocket(okhttp3.WebSocket)

Example 42 with WebSocket

use of okhttp3.WebSocket in project vertx-openshift-it by cescoffier.

the class SimpleHttpIT method testWithWebSocket.

@Test
public void testWithWebSocket() throws MalformedURLException {
    ensureThat("the websocket connection works", () -> {
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(0, TimeUnit.MILLISECONDS).build();
        Request request = new Request.Builder().url(RestAssured.baseURI + "/ws").build();
        List<String> messages = new ArrayList<>();
        WebSocketListener webSocketListener = new WebSocketListener() {

            @Override
            public void onOpen(WebSocket webSocket, okhttp3.Response response) {
                webSocket.send("Hello...");
                webSocket.send("...World!");
                webSocket.close(1000, "Goodbye, World!");
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, okhttp3.Response response) {
                System.err.println("An error has occured: " + t.getMessage());
                t.printStackTrace();
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                messages.add(text);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                messages.add(bytes.utf8());
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                webSocket.close(1000, null);
            }
        };
        client.newWebSocket(request, webSocketListener);
        await().until(() -> messages.size() >= 2);
        Assertions.assertThat(messages).hasSize(2).contains("Hello...", "...World!");
    });
}
Also used : Response(io.restassured.response.Response) WebSocketListener(okhttp3.WebSocketListener) OkHttpClient(okhttp3.OkHttpClient) ByteString(okio.ByteString) Request(okhttp3.Request) ArrayList(java.util.ArrayList) ByteString(okio.ByteString) Matchers.containsString(org.hamcrest.Matchers.containsString) WebSocket(okhttp3.WebSocket) Test(org.junit.Test)

Example 43 with WebSocket

use of okhttp3.WebSocket in project Signal-Android by WhisperSystems.

the class CdshService method getRegisteredUsers.

public Single<ServiceResponse<Map<String, ACI>>> getRegisteredUsers(String username, String password, Set<String> e164Numbers) {
    return Single.create(emitter -> {
        AtomicReference<Stage> stage = new AtomicReference<>(Stage.WAITING_TO_INITIALIZE);
        List<String> addressBook = e164Numbers.stream().map(e -> e.substring(1)).collect(Collectors.toList());
        String url = String.format("%s/discovery/%s/%s", baseUrl, hexPublicKey, hexCodeHash);
        Request request = new Request.Builder().url(url).build();
        WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                switch(stage.get()) {
                    case WAITING_TO_INITIALIZE:
                        enclave.completeHandshake(bytes.toByteArray());
                        byte[] request = enclave.establishedSend(buildPlaintextRequest(username, password, addressBook));
                        stage.set(Stage.WAITING_FOR_RESPONSE);
                        webSocket.send(ByteString.of(request));
                        break;
                    case WAITING_FOR_RESPONSE:
                        byte[] response = enclave.establishedRecv(bytes.toByteArray());
                        try {
                            Map<String, ACI> out = parseResponse(addressBook, response);
                            emitter.onSuccess(ServiceResponse.forResult(out, 200, null));
                        } catch (IOException e) {
                            emitter.onSuccess(ServiceResponse.forUnknownError(e));
                        } finally {
                            webSocket.close(1000, "OK");
                        }
                        break;
                    case FAILURE:
                        Log.w(TAG, "Received a message after we entered the failure state! Ignoring.");
                        webSocket.close(1000, "OK");
                        break;
                }
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                if (code != 1000) {
                    Log.w(TAG, "Remote side is closing with non-normal code " + code);
                    webSocket.close(1000, "Remote closed with code " + code);
                    stage.set(Stage.FAILURE);
                    emitter.onSuccess(ServiceResponse.forApplicationError(new NonSuccessfulResponseCodeException(code), code, null));
                }
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                emitter.onSuccess(ServiceResponse.forApplicationError(t, response != null ? response.code() : 0, null));
                stage.set(Stage.FAILURE);
                webSocket.close(1000, "OK");
            }
        });
        webSocket.send(ByteString.of(enclave.initialRequest()));
        emitter.setCancellable(() -> webSocket.close(1000, "OK"));
    });
}
Also used : DataInputStream(java.io.DataInputStream) SSLContext(javax.net.ssl.SSLContext) Single(io.reactivex.rxjava3.core.Single) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HsmEnclaveClient(org.signal.libsignal.hsmenclave.HsmEnclaveClient) Util(org.whispersystems.signalservice.internal.util.Util) TrustManager(javax.net.ssl.TrustManager) HashMap(java.util.HashMap) WebSocketListener(okhttp3.WebSocketListener) TrustStore(org.whispersystems.signalservice.api.push.TrustStore) AtomicReference(java.util.concurrent.atomic.AtomicReference) Tls12SocketFactory(org.whispersystems.signalservice.api.util.Tls12SocketFactory) Pair(org.whispersystems.libsignal.util.Pair) ByteArrayInputStream(java.io.ByteArrayInputStream) NonSuccessfulResponseCodeException(org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException) Map(java.util.Map) ByteString(okio.ByteString) ConnectionSpec(okhttp3.ConnectionSpec) Response(okhttp3.Response) Log(org.whispersystems.libsignal.logging.Log) Hex(org.whispersystems.signalservice.internal.util.Hex) Request(okhttp3.Request) ACI(org.whispersystems.signalservice.api.push.ACI) Set(java.util.Set) IOException(java.io.IOException) WebSocket(okhttp3.WebSocket) KeyManagementException(java.security.KeyManagementException) UUID(java.util.UUID) ServiceResponse(org.whispersystems.signalservice.internal.ServiceResponse) SignalServiceConfiguration(org.whispersystems.signalservice.internal.configuration.SignalServiceConfiguration) ByteUtil(org.whispersystems.libsignal.util.ByteUtil) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) OkHttpClient(okhttp3.OkHttpClient) X509TrustManager(javax.net.ssl.X509TrustManager) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BlacklistingTrustManager(org.whispersystems.signalservice.internal.util.BlacklistingTrustManager) Collections(java.util.Collections) WebSocketListener(okhttp3.WebSocketListener) ByteString(okio.ByteString) Request(okhttp3.Request) NonSuccessfulResponseCodeException(org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteString(okio.ByteString) IOException(java.io.IOException) WebSocket(okhttp3.WebSocket) Response(okhttp3.Response) ServiceResponse(org.whispersystems.signalservice.internal.ServiceResponse) HashMap(java.util.HashMap) Map(java.util.Map)

Example 44 with WebSocket

use of okhttp3.WebSocket in project java by kubernetes-client.

the class WebSocketsExample method main.

public static void main(String... args) throws ApiException, IOException {
    final ApiClient client = Config.defaultClient();
    WebSockets.stream(args[0], "GET", client, new WebSockets.SocketListener() {

        private volatile WebSocket socket;

        @Override
        public void open(String protocol, WebSocket socket) {
            this.socket = socket;
        }

        @Override
        public void close() {
        }

        @Override
        public void bytesMessage(InputStream is) {
        }

        @Override
        public void failure(Throwable t) {
            t.printStackTrace();
        }

        @Override
        public void textMessage(Reader in) {
            try {
                BufferedReader reader = new BufferedReader(in);
                for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                    System.out.println(line);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });
}
Also used : WebSockets(io.kubernetes.client.util.WebSockets) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) BufferedReader(java.io.BufferedReader) Reader(java.io.Reader) IOException(java.io.IOException) ApiClient(io.kubernetes.client.openapi.ApiClient) WebSocket(okhttp3.WebSocket)

Example 45 with WebSocket

use of okhttp3.WebSocket in project DevRing by LJYcoder.

the class WebSocketManager method removeUrlWebSocketMapping.

/**
 * 移除Url和WebSocket的映射
 */
private void removeUrlWebSocketMapping(WebSocket webSocket) {
    for (Map.Entry<String, WebSocket> entry : mWebSocketPool.entrySet()) {
        if (entry.getValue() == webSocket) {
            String url = entry.getKey();
            mObservableCacheMap.remove(url);
            mWebSocketPool.remove(url);
        }
    }
}
Also used : ByteString(okio.ByteString) Map(java.util.Map) HashMap(java.util.HashMap) WebSocket(okhttp3.WebSocket)

Aggregations

WebSocket (okhttp3.WebSocket)42 MockResponse (mockwebserver3.MockResponse)27 Test (org.junit.jupiter.api.Test)27 WebSocketListener (okhttp3.WebSocketListener)25 ByteString (okio.ByteString)20 Request (okhttp3.Request)16 Response (okhttp3.Response)9 OkHttpClient (okhttp3.OkHttpClient)8 IOException (java.io.IOException)5 HashMap (java.util.HashMap)5 Map (java.util.Map)5 CountDownLatch (java.util.concurrent.CountDownLatch)4 Test (org.junit.Test)4 RecordedRequest (mockwebserver3.RecordedRequest)3 Single (io.reactivex.rxjava3.core.Single)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 DataInputStream (java.io.DataInputStream)2 InputStream (java.io.InputStream)2 StandardCharsets (java.nio.charset.StandardCharsets)2