Search in sources :

Example 1 with WebSocketAdapter

use of com.neovisionaries.ws.client.WebSocketAdapter in project ninja by ninjaframework.

the class ChatWebSocketTest method sendAndReceiveText.

@Test
public void sendAndReceiveText() throws IOException, WebSocketException, InterruptedException {
    String chatId = UUID.randomUUID().toString();
    String url = withBaseWebSocketUrl("/chat");
    WebSocket ws = new WebSocketFactory().createSocket(url);
    try {
        ws.addHeader("X-Chat-Id", chatId);
        ws.connect();
        BlockingQueue<String> received = new LinkedBlockingQueue<>();
        ws.addListener(new WebSocketAdapter() {

            @Override
            public void onTextMessage(WebSocket ws, String text) throws Exception {
                received.put(text);
            }
        });
        ws.sendText("chat-id");
        String reply = received.poll(2L, TimeUnit.SECONDS);
        assertThat(reply, is(chatId));
    } finally {
        ws.disconnect(WebSocketCloseCode.NORMAL);
    }
}
Also used : WebSocketAdapter(com.neovisionaries.ws.client.WebSocketAdapter) WebSocketFactory(com.neovisionaries.ws.client.WebSocketFactory) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) OpeningHandshakeException(com.neovisionaries.ws.client.OpeningHandshakeException) IOException(java.io.IOException) WebSocketException(com.neovisionaries.ws.client.WebSocketException) WebSocket(com.neovisionaries.ws.client.WebSocket) Test(org.junit.Test)

Example 2 with WebSocketAdapter

use of com.neovisionaries.ws.client.WebSocketAdapter in project Slide by ccrama.

the class LiveThread method doLiveThreadUpdates.

public void doLiveThreadUpdates() {
    final PaginatorAdapter adapter = new PaginatorAdapter(this);
    baseRecycler.setAdapter(adapter);
    doLiveSidebar();
    if (thread.getWebsocketUrl() != null && !thread.getWebsocketUrl().isEmpty()) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                final ObjectReader o = new ObjectMapper().reader();
                try {
                    WebSocket ws = new WebSocketFactory().createSocket(thread.getWebsocketUrl());
                    ws.addListener(new WebSocketAdapter() {

                        @Override
                        public void onTextMessage(WebSocket websocket, String s) {
                            LogUtil.v("Recieved" + s);
                            if (s.contains("\"type\": \"update\"")) {
                                try {
                                    LiveUpdate u = new LiveUpdate(o.readTree(s).get("payload").get("data"));
                                    updates.add(0, u);
                                    runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            adapter.notifyItemInserted(0);
                                            baseRecycler.smoothScrollToPosition(0);
                                        }
                                    });
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            } else if (s.contains("embeds_ready")) {
                                String node = updates.get(0).getDataNode().toString();
                                LogUtil.v("Getting");
                                try {
                                    node = node.replace("\"embeds\":[]", "\"embeds\":" + o.readTree(s).get("payload").get("media_embeds").toString());
                                    LiveUpdate u = new LiveUpdate(o.readTree(node));
                                    updates.set(0, u);
                                    runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            adapter.notifyItemChanged(0);
                                        }
                                    });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        /* todoelse if(s.contains("delete")){
                                    updates.remove(0);
                                    adapter.notifyItemRemoved(0);
                                }*/
                        }
                    });
                    ws.connect();
                } catch (IOException | WebSocketException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}
Also used : IOException(java.io.IOException) WebSocketException(com.neovisionaries.ws.client.WebSocketException) IOException(java.io.IOException) WebSocket(com.neovisionaries.ws.client.WebSocket) LiveUpdate(net.dean.jraw.models.LiveUpdate) WebSocketAdapter(com.neovisionaries.ws.client.WebSocketAdapter) WebSocketFactory(com.neovisionaries.ws.client.WebSocketFactory) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 3 with WebSocketAdapter

use of com.neovisionaries.ws.client.WebSocketAdapter in project Javacord by BtoBastian.

the class DiscordWebSocketAdapter method sendIdentify.

/**
 * Sends the identify packet.
 *
 * @param websocket The websocket the identify packet should be sent to.
 */
private void sendIdentify(WebSocket websocket) {
    ObjectNode identifyPacket = JsonNodeFactory.instance.objectNode().put("op", GatewayOpcode.IDENTIFY.getCode());
    ObjectNode data = identifyPacket.putObject("d");
    String token = api.getPrefixedToken();
    data.put("token", token).put("compress", true).put("large_threshold", 250).putObject("properties").put("$os", System.getProperty("os.name")).put("$browser", "Javacord").put("$device", "Javacord").put("$referrer", "").put("$referring_domain", "");
    data.put("intents", Intent.calculateBitmask(api.getIntents().toArray(new Intent[0])));
    if (api.getTotalShards() > 1) {
        data.putArray("shard").add(api.getCurrentShard()).add(api.getTotalShards());
    }
    // remove eventually still registered listeners
    synchronized (identifyFrameListeners) {
        websocket.removeListeners(identifyFrameListeners);
        identifyFrameListeners.clear();
    }
    WebSocketFrame identifyFrame = WebSocketFrame.createTextFrame(identifyPacket.toString());
    lastSentFrameWasIdentify.set(identifyFrame, false);
    WebSocketAdapter identifyFrameListener = new WebSocketAdapter() {

        @Override
        public void onFrameSent(WebSocket websocket, WebSocketFrame frame) {
            if (lastSentFrameWasIdentify.isMarked()) {
                // sending non-heartbeat frame after identify was sent => unset mark
                if (!nextHeartbeatFrame.compareAndSet(frame, null)) {
                    lastSentFrameWasIdentify.set(null, false);
                    websocket.removeListener(this);
                    identifyFrameListeners.remove(this);
                }
            } else {
                // identify frame is actually sent => set the mark
                lastSentFrameWasIdentify.compareAndSet(frame, null, false, true);
            }
        }
    };
    identifyFrameListeners.add(identifyFrameListener);
    websocket.addListener(identifyFrameListener);
    logger.debug("Sending identify packet");
    sendLifecycleFrame(websocket, identifyFrame);
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) WebSocketAdapter(com.neovisionaries.ws.client.WebSocketAdapter) WebSocketFrame(com.neovisionaries.ws.client.WebSocketFrame) WebSocket(com.neovisionaries.ws.client.WebSocket)

Example 4 with WebSocketAdapter

use of com.neovisionaries.ws.client.WebSocketAdapter in project ninja by ninjaframework.

the class ChatWebSocketTest method sendAndReceiveBinary.

@Test
public void sendAndReceiveBinary() throws IOException, WebSocketException, InterruptedException {
    String chatId = UUID.randomUUID().toString();
    String url = withBaseWebSocketUrl("/chat");
    WebSocket ws = new WebSocketFactory().createSocket(url);
    try {
        ws.addHeader("X-Chat-Id", chatId);
        ws.connect();
        BlockingQueue<byte[]> received = new LinkedBlockingQueue<>();
        ws.addListener(new WebSocketAdapter() {

            @Override
            public void onBinaryMessage(WebSocket websocket, byte[] binary) throws Exception {
                received.put(binary);
            }
        });
        ws.sendText("binary1");
        byte[] reply = received.poll(2L, TimeUnit.SECONDS);
        assertThat(reply, is(ChatWebSocket.BINARY1));
    } finally {
        ws.disconnect(WebSocketCloseCode.NORMAL);
    }
}
Also used : WebSocketAdapter(com.neovisionaries.ws.client.WebSocketAdapter) WebSocketFactory(com.neovisionaries.ws.client.WebSocketFactory) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) OpeningHandshakeException(com.neovisionaries.ws.client.OpeningHandshakeException) IOException(java.io.IOException) WebSocketException(com.neovisionaries.ws.client.WebSocketException) WebSocket(com.neovisionaries.ws.client.WebSocket) Test(org.junit.Test)

Aggregations

WebSocket (com.neovisionaries.ws.client.WebSocket)4 WebSocketAdapter (com.neovisionaries.ws.client.WebSocketAdapter)4 WebSocketException (com.neovisionaries.ws.client.WebSocketException)3 WebSocketFactory (com.neovisionaries.ws.client.WebSocketFactory)3 IOException (java.io.IOException)3 OpeningHandshakeException (com.neovisionaries.ws.client.OpeningHandshakeException)2 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)2 Test (org.junit.Test)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ObjectReader (com.fasterxml.jackson.databind.ObjectReader)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 WebSocketFrame (com.neovisionaries.ws.client.WebSocketFrame)1 LiveUpdate (net.dean.jraw.models.LiveUpdate)1