Search in sources :

Example 1 with WebSocket

use of com.neovisionaries.ws.client.WebSocket 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 WebSocket

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

the class ChatWebSocketTest method supportedProtocol.

@Test
public void supportedProtocol() throws IOException, WebSocketException {
    String url = withBaseWebSocketUrl("/chat");
    WebSocket ws = new WebSocketFactory().createSocket(url);
    try {
        ws.addProtocol("chat");
        ws.connect();
        assertThat(ws.getAgreedProtocol(), is("chat"));
    } finally {
        ws.disconnect(WebSocketCloseCode.NORMAL);
    }
}
Also used : WebSocketFactory(com.neovisionaries.ws.client.WebSocketFactory) WebSocket(com.neovisionaries.ws.client.WebSocket) Test(org.junit.Test)

Example 3 with WebSocket

use of com.neovisionaries.ws.client.WebSocket in project FlareBot by FlareBot.

the class WebSocketFactory method createSocket.

@Override
public WebSocket createSocket(URL url) throws IOException {
    WebSocket socket = super.createSocket(url);
    socket.addListener(this.listener);
    return socket;
}
Also used : WebSocket(com.neovisionaries.ws.client.WebSocket)

Example 4 with WebSocket

use of com.neovisionaries.ws.client.WebSocket 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 5 with WebSocket

use of com.neovisionaries.ws.client.WebSocket 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)

Aggregations

WebSocket (com.neovisionaries.ws.client.WebSocket)17 WebSocketFactory (com.neovisionaries.ws.client.WebSocketFactory)10 WebSocketAdapter (com.neovisionaries.ws.client.WebSocketAdapter)6 Test (org.junit.Test)6 WebSocketException (com.neovisionaries.ws.client.WebSocketException)5 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)3 OpeningHandshakeException (com.neovisionaries.ws.client.OpeningHandshakeException)3 WebSocketFrame (com.neovisionaries.ws.client.WebSocketFrame)3 IOException (java.io.IOException)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 JsonNodeFactory (com.fasterxml.jackson.databind.node.JsonNodeFactory)2 ProxySettings (com.neovisionaries.ws.client.ProxySettings)2 WebSocketListener (com.neovisionaries.ws.client.WebSocketListener)2 InetSocketAddress (java.net.InetSocketAddress)2 PasswordAuthentication (java.net.PasswordAuthentication)2 Proxy (java.net.Proxy)2 ProxySelector (java.net.ProxySelector)2 SocketAddress (java.net.SocketAddress)2