Search in sources :

Example 1 with WebSocket

use of com.koushikdutta.async.http.WebSocket in project AndroidAsync by koush.

the class SocketIOConnection method reconnect.

void reconnect(final DependentCancellable child) {
    if (isConnected()) {
        return;
    }
    // if a connection is in progress, just wait.
    if (connecting != null && !connecting.isDone() && !connecting.isCancelled()) {
        if (child != null)
            child.setParent(connecting);
        return;
    }
    request.logi("Reconnecting socket.io");
    connecting = httpClient.executeString(request, null).then(new TransformFuture<SocketIOTransport, String>() {

        @Override
        protected void transform(String result) throws Exception {
            String[] parts = result.split(":");
            final String sessionId = parts[0];
            if (!"".equals(parts[1]))
                heartbeat = Integer.parseInt(parts[1]) / 2 * 1000;
            else
                heartbeat = 0;
            String transportsLine = parts[3];
            String[] transports = transportsLine.split(",");
            HashSet<String> set = new HashSet<String>(Arrays.asList(transports));
            final SimpleFuture<SocketIOTransport> transport = new SimpleFuture<SocketIOTransport>();
            if (set.contains("websocket")) {
                final String sessionUrl = Uri.parse(request.getUri().toString()).buildUpon().appendPath("websocket").appendPath(sessionId).build().toString();
                httpClient.websocket(sessionUrl, null, null).setCallback(new FutureCallback<WebSocket>() {

                    @Override
                    public void onCompleted(Exception e, WebSocket result) {
                        if (e != null) {
                            transport.setComplete(e);
                            return;
                        }
                        transport.setComplete(new WebSocketTransport(result, sessionId));
                    }
                });
            } else if (set.contains("xhr-polling")) {
                final String sessionUrl = Uri.parse(request.getUri().toString()).buildUpon().appendPath("xhr-polling").appendPath(sessionId).build().toString();
                XHRPollingTransport xhrPolling = new XHRPollingTransport(httpClient, sessionUrl, sessionId);
                transport.setComplete(xhrPolling);
            } else {
                throw new SocketIOException("transport not supported");
            }
            setComplete(transport);
        }
    }).setCallback(new FutureCallback<SocketIOTransport>() {

        @Override
        public void onCompleted(Exception e, SocketIOTransport result) {
            if (e != null) {
                reportDisconnect(e);
                return;
            }
            reconnectDelay = request.config.reconnectDelay;
            SocketIOConnection.this.transport = result;
            attach();
        }
    });
    if (child != null)
        child.setParent(connecting);
}
Also used : WebSocket(com.koushikdutta.async.http.WebSocket) SocketIOTransport(com.koushikdutta.async.http.socketio.transport.SocketIOTransport) WebSocketTransport(com.koushikdutta.async.http.socketio.transport.WebSocketTransport) XHRPollingTransport(com.koushikdutta.async.http.socketio.transport.XHRPollingTransport) FutureCallback(com.koushikdutta.async.future.FutureCallback) HashSet(java.util.HashSet) SimpleFuture(com.koushikdutta.async.future.SimpleFuture)

Example 2 with WebSocket

use of com.koushikdutta.async.http.WebSocket in project AndroidAsync by koush.

the class WebSocketTests method testWebSocket.

public void testWebSocket() throws Exception {
    final Semaphore semaphore = new Semaphore(0);
    AsyncHttpClient.getDefaultInstance().websocket("http://localhost:5000/ws", null, new WebSocketConnectCallback() {

        @Override
        public void onCompleted(Exception ex, WebSocket webSocket) {
            webSocket.send("hello");
            webSocket.setStringCallback(new StringCallback() {

                @Override
                public void onStringAvailable(String s) {
                    assertEquals(s, "hello");
                    semaphore.release();
                }
            });
        }
    });
    assertTrue(semaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS));
}
Also used : WebSocketConnectCallback(com.koushikdutta.async.http.AsyncHttpClient.WebSocketConnectCallback) StringCallback(com.koushikdutta.async.http.WebSocket.StringCallback) Semaphore(java.util.concurrent.Semaphore) WebSocket(com.koushikdutta.async.http.WebSocket)

Example 3 with WebSocket

use of com.koushikdutta.async.http.WebSocket in project AndroidAsync by koush.

the class IssueWithWebSocketFuturesTests method testWebSocketFutureWithHandshakeFailureCallback.

//testing that websocket callback gets called with the correct parameters.
public void testWebSocketFutureWithHandshakeFailureCallback() throws Exception {
    //creating a faulty server!
    AsyncHttpServer httpServer = new AsyncHttpServer();
    httpServer.websocket(".*", new AsyncHttpServer.WebSocketRequestCallback() {

        @Override
        public void onConnected(WebSocket webSocket, AsyncHttpServerRequest request) {
        }
    });
    httpServer.listen(6666);
    final Exception[] callbackException = { null };
    final WebSocket[] callbackWs = { null };
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    //for some reason, it fails with a WebSocketHandshakeException.
    //But in general, if the handshake fails, the callback must be called with an exception.
    Future<WebSocket> wsFuture = AsyncHttpClient.getDefaultInstance().websocket("ws://127.0.0.1:6666", "ws", new AsyncHttpClient.WebSocketConnectCallback() {

        @Override
        public void onCompleted(Exception ex, WebSocket webSocket) {
            callbackException[0] = ex;
            callbackWs[0] = webSocket;
            countDownLatch.countDown();
        }
    });
    //wait for the future to complete
    countDownLatch.await();
    //exactly one mut be null
    assertTrue(callbackWs[0] == null ^ callbackException[0] == null);
    //callback parameters must be the same as the future's result
    assertEquals(wsFuture.tryGet(), callbackWs[0]);
    assertEquals(wsFuture.tryGetException(), callbackException[0]);
}
Also used : AsyncHttpServerRequest(com.koushikdutta.async.http.server.AsyncHttpServerRequest) AsyncHttpServer(com.koushikdutta.async.http.server.AsyncHttpServer) CountDownLatch(java.util.concurrent.CountDownLatch) WebSocket(com.koushikdutta.async.http.WebSocket) AsyncHttpClient(com.koushikdutta.async.http.AsyncHttpClient)

Example 4 with WebSocket

use of com.koushikdutta.async.http.WebSocket in project K6nele by Kaljurand.

the class WebSocketRecognitionService method startSocket.

/**
     * Opens the socket and starts recording/sending.
     *
     * @param url Webservice URL
     */
void startSocket(String url) {
    mIsEosSent = false;
    Log.i(url);
    AsyncHttpClient client = AsyncHttpClient.getDefaultInstance();
    if (false) {
        //http://stackoverflow.com/questions/37804816/androidasync-how-to-create-ssl-client-in-websocket-connection
        AsyncSSLSocketMiddleware sslSocketMiddleware = new AsyncSSLSocketMiddleware(client);
        SSLContext sslContext = null;
        try {
            sslContext = getSSLContext();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        sslSocketMiddleware.setSSLContext(sslContext);
        client.insertMiddleware(sslSocketMiddleware);
    }
    client.websocket(url, PROTOCOL, new AsyncHttpClient.WebSocketConnectCallback() {

        @Override
        public void onCompleted(Exception ex, final WebSocket webSocket) {
            mWebSocket = webSocket;
            if (ex != null) {
                handleException(ex);
                return;
            }
            webSocket.setStringCallback(new WebSocket.StringCallback() {

                public void onStringAvailable(String s) {
                    Log.i(s);
                    handleResult(s);
                }
            });
            webSocket.setClosedCallback(new CompletedCallback() {

                @Override
                public void onCompleted(Exception ex) {
                    if (ex == null) {
                        Log.e("ClosedCallback");
                        handleFinish(mIsEosSent);
                    } else {
                        Log.e("ClosedCallback: ", ex);
                        handleException(ex);
                    }
                }
            });
            webSocket.setEndCallback(new CompletedCallback() {

                @Override
                public void onCompleted(Exception ex) {
                    if (ex == null) {
                        Log.e("EndCallback");
                        handleFinish(mIsEosSent);
                    } else {
                        Log.e("EndCallback: ", ex);
                        handleException(ex);
                    }
                }
            });
            startSending(webSocket);
        }
    });
}
Also used : AsyncSSLSocketMiddleware(com.koushikdutta.async.http.AsyncSSLSocketMiddleware) CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AsyncHttpClient(com.koushikdutta.async.http.AsyncHttpClient) WebSocket(com.koushikdutta.async.http.WebSocket)

Example 5 with WebSocket

use of com.koushikdutta.async.http.WebSocket in project AndroidAsync by koush.

the class WebSocketTests method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    httpServer = new AsyncHttpServer();
    httpServer.setErrorCallback(new CompletedCallback() {

        @Override
        public void onCompleted(Exception ex) {
            fail();
        }
    });
    httpServer.listen(AsyncServer.getDefault(), 5000);
    httpServer.websocket("/ws", new WebSocketRequestCallback() {

        @Override
        public void onConnected(final WebSocket webSocket, AsyncHttpServerRequest request) {
            webSocket.setStringCallback(new StringCallback() {

                @Override
                public void onStringAvailable(String s) {
                    webSocket.send(s);
                }
            });
        }
    });
}
Also used : CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) WebSocketRequestCallback(com.koushikdutta.async.http.server.AsyncHttpServer.WebSocketRequestCallback) AsyncHttpServerRequest(com.koushikdutta.async.http.server.AsyncHttpServerRequest) AsyncHttpServer(com.koushikdutta.async.http.server.AsyncHttpServer) StringCallback(com.koushikdutta.async.http.WebSocket.StringCallback) WebSocket(com.koushikdutta.async.http.WebSocket)

Aggregations

WebSocket (com.koushikdutta.async.http.WebSocket)6 CompletedCallback (com.koushikdutta.async.callback.CompletedCallback)3 AsyncHttpClient (com.koushikdutta.async.http.AsyncHttpClient)2 WebSocketConnectCallback (com.koushikdutta.async.http.AsyncHttpClient.WebSocketConnectCallback)2 StringCallback (com.koushikdutta.async.http.WebSocket.StringCallback)2 AsyncHttpServer (com.koushikdutta.async.http.server.AsyncHttpServer)2 AsyncHttpServerRequest (com.koushikdutta.async.http.server.AsyncHttpServerRequest)2 IOException (java.io.IOException)2 Uri (android.net.Uri)1 FutureCallback (com.koushikdutta.async.future.FutureCallback)1 SimpleFuture (com.koushikdutta.async.future.SimpleFuture)1 AsyncHttpGet (com.koushikdutta.async.http.AsyncHttpGet)1 AsyncHttpRequest (com.koushikdutta.async.http.AsyncHttpRequest)1 AsyncSSLSocketMiddleware (com.koushikdutta.async.http.AsyncSSLSocketMiddleware)1 WebSocketRequestCallback (com.koushikdutta.async.http.server.AsyncHttpServer.WebSocketRequestCallback)1 SocketIOTransport (com.koushikdutta.async.http.socketio.transport.SocketIOTransport)1 WebSocketTransport (com.koushikdutta.async.http.socketio.transport.WebSocketTransport)1 XHRPollingTransport (com.koushikdutta.async.http.socketio.transport.XHRPollingTransport)1 KeyManagementException (java.security.KeyManagementException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1