org.eclipse.jetty.websocket.client.WebSocketClient Java Examples

The following examples show how to use org.eclipse.jetty.websocket.client.WebSocketClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NotebookServerTest.java    From submarine with Apache License 2.0 7 votes vote down vote up
@Test
public void testWebsocketConnection() throws Exception{
  URI uri = URI.create(
      AbstractSubmarineServerTest.getWebsocketApiUrlToTest());
  WebSocketClient client = new WebSocketClient();
  try {
    client.start();
    // The socket that receives events
    EventSocket socket = new EventSocket();
    // Attempt Connect
    Future<Session> fut = client.connect(socket, uri);
    // Wait for Connect
    Session session = fut.get();
    // Send a message
    session.getRemote().sendString("Hello");
    // Close session
    //session.close();
    session.close(StatusCode.NORMAL, "I'm done");
  } finally {
    client.stop();
  }
}
 
Example #2
Source File: RosBridge.java    From java_rosbridge with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Connects to the Rosbridge host at the provided URI.
 * @param rosBridgeURI the URI to the ROS Bridge websocket server. Note that ROS Bridge by default uses port 9090. An example URI is: ws://localhost:9090
 * @param waitForConnection if true, then this method will block until the connection is established. If false, then return immediately.
 */
public void connect(String rosBridgeURI, boolean waitForConnection){
	WebSocketClient client = new WebSocketClient();
	try {
		client.start();
		URI echoUri = new URI(rosBridgeURI);
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		client.connect(this, echoUri, request);
		System.out.printf("Connecting to : %s%n", echoUri);
		if(waitForConnection){
			this.waitForConnection();
		}

	} catch (Throwable t) {
		t.printStackTrace();
	}

}
 
Example #3
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test(timeOut = 10000)
public void emptySubcriptionConsumerTest() throws Exception {

    // Empty subcription name
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get()
            + "/ws/v2/consumer/persistent/my-property/my-ns/my-topic2/?subscriptionType=Exclusive";
    URI consumeUri = URI.create(consumerUri);

    WebSocketClient consumeClient1 = new WebSocketClient();
    SimpleConsumerSocket consumeSocket1 = new SimpleConsumerSocket();

    try {
        consumeClient1.start();
        ClientUpgradeRequest consumeRequest1 = new ClientUpgradeRequest();
        Future<Session> consumerFuture1 = consumeClient1.connect(consumeSocket1, consumeUri, consumeRequest1);
        consumerFuture1.get();
        fail("should fail: empty subscription");
    } catch (Exception e) {
        // Expected
        assertTrue(e.getCause() instanceof UpgradeException);
        assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(),
                HttpServletResponse.SC_BAD_REQUEST);
    } finally {
        stopWebSocketClient(consumeClient1);
    }
}
 
Example #4
Source File: CoinbaseSocket.java    From cloud-bigtable-examples with Apache License 2.0 6 votes vote down vote up
@Override
public boolean start() throws IOException {
  String destUri = "wss://ws-feed.exchange.coinbase.com";
  WebSocketClient client = new WebSocketClient(new SslContextFactory());
  try {
    LOG.info("connecting to coinbsae feed");
    client.start();
    URI echoUri = new URI(destUri);
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    client.connect(this, echoUri, request);
    LOG.info("done connecting");
  } catch (Throwable t) {
    t.printStackTrace();
  }
  return advance();
}
 
Example #5
Source File: JsonWebSocketProtocolHandler.java    From diozero with MIT License 6 votes vote down vote up
public JsonWebSocketProtocolHandler(NativeDeviceFactoryInterface deviceFactory) {
	super(deviceFactory);

	serialiser = GSON::toJson;
	deserialiser = GSON::fromJson;
	
	webSocketClient = new WebSocketClient();
	try {
		webSocketClient.start();

		URI uri = new URI("ws://localhost:8080/diozero");
		Logger.debug("Connecting to: {}...", uri);
		session = webSocketClient.connect(this, uri, new ClientUpgradeRequest()).get();
		Logger.debug("Connected to: {}", uri);
	} catch (Exception e) {
		throw new RuntimeIOException(e);
	}
}
 
Example #6
Source File: LoggregatorClient.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
public void start(Target target, String loggregatorLocation, LoggregatorListener listener) throws Exception {
	logger.debug(NLS.bind("About to connect: {0}", loggregatorLocation));

	SslContextFactory sslContextFactory = new SslContextFactory(true);
	WebSocketClient client = new WebSocketClient(sslContextFactory);
	LoggregatorSocket socket = new LoggregatorSocket(listener);
	try {
		client.start();
		URI loggregatorUri = new URI(loggregatorLocation);
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		request.setHeader("Authorization", "bearer " + target.getCloud().getAccessToken().getString("access_token"));

		client.connect(socket, loggregatorUri, request);
		logger.debug(NLS.bind("Connecting to: {0}", loggregatorUri));
		socket.awaitClose(25, TimeUnit.SECONDS);
	} finally {
		client.stop();
	}
}
 
Example #7
Source File: SimpleEchoClient.java    From java_rosbridge with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) {
	String destUri = "ws://echo.websocket.org";
	if (args.length > 0) {
		destUri = args[0];
	}
	WebSocketClient client = new WebSocketClient();
	SimpleEchoSocket socket = new SimpleEchoSocket();
	try {
		client.start();
		URI echoUri = new URI(destUri);
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		client.connect(socket, echoUri, request);
		System.out.printf("Connecting to : %s%n", echoUri);
		socket.awaitClose(15, TimeUnit.SECONDS);
	} catch (Throwable t) {
		t.printStackTrace();
	} finally {
		try {
			client.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example #8
Source File: BuckClient.java    From buck with Apache License 2.0 6 votes vote down vote up
BuckClient(final BuckEventsHandlerInterface buckEventHandler, Project project) {
  mWSClient = new WebSocketClient();
  mProject = project;
  mConnecting = new AtomicBoolean(false);

  mBuckSocket =
      new BuckSocket(
          new BuckEventsHandlerInterface() {
            @Override
            public void onConnect() {
              buckEventHandler.onConnect();
              mConnecting.set(false);
            }

            @Override
            public void onDisconnect() {
              buckEventHandler.onDisconnect();
            }

            @Override
            public void onMessage(String message) {
              buckEventHandler.onMessage(message);
            }
          });
}
 
Example #9
Source File: SwingClient.java    From codenjoy with GNU General Public License v3.0 6 votes vote down vote up
private void connect() {
    try {
        // TODO to use board url parsing like WebSocketRunner.runClient
        String server = String.format("ws://%s/codenjoy-contest/ws", SERVER_AND_PORT);
        URI uri = new URI(String.format("%s?user=%s&code=%s", server, USER_ID, CODE));

        if (session != null) {
            session.close();
        }

        cc = new WebSocketClient();
        cc.start();
        session = cc.connect(new ClientSocket(), uri).get(5000, TimeUnit.MILLISECONDS);
    } catch (Exception ex) {
        textArea.append(ex.toString());
    }
}
 
Example #10
Source File: SonyAudioConnection.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
public SonyAudioConnection(String host, int port, String path, SonyAudioEventListener listener,
        ScheduledExecutorService scheduler, WebSocketClient webSocketClient) throws URISyntaxException {
    this.host = host;
    this.port = port;
    this.path = path;
    this.listener = listener;
    this.gson = new Gson();
    this.webSocketClient = webSocketClient;

    base_uri = new URI(String.format("ws://%s:%d/%s", host, port, path)).normalize();

    URI wsAvContentUri = base_uri.resolve(base_uri.getPath() + "/avContent").normalize();
    avContentSocket = new SonyAudioClientSocket(this, wsAvContentUri, scheduler);
    URI wsAudioUri = base_uri.resolve(base_uri.getPath() + "/audio").normalize();
    audioSocket = new SonyAudioClientSocket(this, wsAudioUri, scheduler);

    URI wsSystemUri = base_uri.resolve(base_uri.getPath() + "/system").normalize();
    systemSocket = new SonyAudioClientSocket(this, wsSystemUri, scheduler);
}
 
Example #11
Source File: JettyWebSocketClient.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@OnEnabled
@Override
public void startClient(final ConfigurationContext context) throws Exception{

    final SSLContextService sslService = context.getProperty(SSL_CONTEXT).asControllerService(SSLContextService.class);
    SslContextFactory sslContextFactory = null;
    if (sslService != null) {
        sslContextFactory = createSslFactory(sslService, false, false);
    }
    client = new WebSocketClient(sslContextFactory);

    configurePolicy(context, client.getPolicy());

    client.start();

    webSocketUri = new URI(context.getProperty(WS_URI).getValue());
    connectionTimeoutMillis = context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS);
}
 
Example #12
Source File: BoseSoundTouchHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private synchronized void openConnection() {
    closeConnection();
    try {
        client = new WebSocketClient();
        // we need longer timeouts for web socket.
        client.setMaxIdleTimeout(360 * 1000);
        // Port seems to be hard coded, therefore no user input or discovery is necessary
        String wsUrl = "ws://" + getIPAddress() + ":8080/";
        logger.debug("{}: Connecting to: {}", getDeviceName(), wsUrl);
        ClientUpgradeRequest request = new ClientUpgradeRequest();
        request.setSubProtocols("gabbo");
        client.setStopTimeout(1000);
        client.start();
        client.connect(this, new URI(wsUrl), request);
    } catch (Exception e) {
        onWebSocketError(e);
    }
}
 
Example #13
Source File: RemoteDataset.java    From dawnsci with Eclipse Public License 1.0 6 votes vote down vote up
private void createFileListener() throws Exception {
	
       URI uri = URI.create(urlBuilder.getEventURL());

       this.client = new WebSocketClient(exec);
       client.start();
      
       final DataEventSocket clientSocket = new DataEventSocket();
       // Attempt Connect
       Future<Session> fut = client.connect(clientSocket, uri);

       // Wait for Connect
       connection = fut.get();

       // Send a message
       connection.getRemote().sendString("Connected to "+urlBuilder.getPath());
}
 
Example #14
Source File: WebClientFactoryTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGetClients() throws Exception {
    HttpClient httpClient = webClientFactory.getCommonHttpClient();
    WebSocketClient webSocketClient = webClientFactory.getCommonWebSocketClient();

    assertThat(httpClient, is(notNullValue()));
    assertThat(webSocketClient, is(notNullValue()));
}
 
Example #15
Source File: WebSocketRunner.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
private WebSocketClient createClient() {
    if (UrlParser.WSS_PROTOCOL.equals(uri.getScheme())) {
        SslContextFactory ssl = new SslContextFactory(true);
        ssl.setValidateCerts(false);
        return new WebSocketClient(ssl);
    }

    if (UrlParser.WS_PROTOCOL.equals(uri.getScheme())) {
        return new WebSocketClient();
    }

    throw new UnsupportedOperationException("Unsupported WebSocket protocol: " + uri.getScheme());
}
 
Example #16
Source File: WebClientFactoryImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@Deprecated
public WebSocketClient createWebSocketClient(String consumerName, String endpoint) {
    Objects.requireNonNull(endpoint, "endpoint must not be null");
    logger.debug("web socket client for endpoint {} requested", endpoint);
    checkConsumerName(consumerName);
    return createWebSocketClientInternal(consumerName, endpoint, false, null);
}
 
Example #17
Source File: V1_ProxyAuthenticationTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public void socketTest() throws Exception {
    final String topic = "prop/use/my-ns/my-topic1";
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/consumer/persistent/" + topic + "/my-sub";
    final String producerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/producer/persistent/" + topic;
    URI consumeUri = URI.create(consumerUri);
    URI produceUri = URI.create(producerUri);

    consumeClient = new WebSocketClient();
    SimpleConsumerSocket consumeSocket = new SimpleConsumerSocket();
    produceClient = new WebSocketClient();
    SimpleProducerSocket produceSocket = new SimpleProducerSocket();

    consumeClient.start();
    ClientUpgradeRequest consumeRequest = new ClientUpgradeRequest();
    Future<Session> consumerFuture = consumeClient.connect(consumeSocket, consumeUri, consumeRequest);
    log.info("Connecting to : {}", consumeUri);

    ClientUpgradeRequest produceRequest = new ClientUpgradeRequest();
    produceClient.start();
    Future<Session> producerFuture = produceClient.connect(produceSocket, produceUri, produceRequest);
    Assert.assertTrue(consumerFuture.get().isOpen());
    Assert.assertTrue(producerFuture.get().isOpen());

    consumeSocket.awaitClose(1, TimeUnit.SECONDS);
    produceSocket.awaitClose(1, TimeUnit.SECONDS);
    Assert.assertTrue(produceSocket.getBuffer().size() > 0);
    Assert.assertEquals(produceSocket.getBuffer(), consumeSocket.getBuffer());
}
 
Example #18
Source File: WebClientFactoryTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGetWebSocketClientWithEndpoint() throws Exception {
    when(trustmanagerProvider.getTrustManagers("https://www.heise.de")).thenReturn(Stream.empty());

    WebSocketClient webSocketClient = webClientFactory.createWebSocketClient("consumer", TEST_URL);

    assertThat(webSocketClient, is(notNullValue()));
    verify(trustmanagerProvider).getTrustManagers(TEST_URL);
    webSocketClient.stop();
}
 
Example #19
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 10000)
public void conflictingConsumerTest() throws Exception {
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get()
            + "/ws/v2/consumer/persistent/my-property/my-ns/my-topic3/sub1?subscriptionType=Exclusive";
    URI consumeUri = URI.create(consumerUri);

    WebSocketClient consumeClient1 = new WebSocketClient();
    WebSocketClient consumeClient2 = new WebSocketClient();
    SimpleConsumerSocket consumeSocket1 = new SimpleConsumerSocket();
    SimpleConsumerSocket consumeSocket2 = new SimpleConsumerSocket();

    try {
        consumeClient1.start();
        ClientUpgradeRequest consumeRequest1 = new ClientUpgradeRequest();
        Future<Session> consumerFuture1 = consumeClient1.connect(consumeSocket1, consumeUri, consumeRequest1);
        consumerFuture1.get();

        try {
            consumeClient2.start();
            ClientUpgradeRequest consumeRequest2 = new ClientUpgradeRequest();
            Future<Session> consumerFuture2 = consumeClient2.connect(consumeSocket2, consumeUri, consumeRequest2);
            consumerFuture2.get();
            fail("should fail: conflicting subscription name");
        } catch (Exception e) {
            // Expected
            assertTrue(e.getCause() instanceof UpgradeException);
            assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(),
                    HttpServletResponse.SC_CONFLICT);
        } finally {
            stopWebSocketClient(consumeClient2);
        }
    } finally {
        stopWebSocketClient(consumeClient1);
    }
}
 
Example #20
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 10000)
public void conflictingProducerTest() throws Exception {
    final String producerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get()
            + "/ws/v2/producer/persistent/my-property/my-ns/my-topic4?producerName=my-producer";
    URI produceUri = URI.create(producerUri);

    WebSocketClient produceClient1 = new WebSocketClient();
    WebSocketClient produceClient2 = new WebSocketClient();
    SimpleProducerSocket produceSocket1 = new SimpleProducerSocket();
    SimpleProducerSocket produceSocket2 = new SimpleProducerSocket();

    try {
        produceClient1.start();
        ClientUpgradeRequest produceRequest1 = new ClientUpgradeRequest();
        Future<Session> producerFuture1 = produceClient1.connect(produceSocket1, produceUri, produceRequest1);
        producerFuture1.get();

        try {
            produceClient2.start();
            ClientUpgradeRequest produceRequest2 = new ClientUpgradeRequest();
            Future<Session> producerFuture2 = produceClient2.connect(produceSocket2, produceUri, produceRequest2);
            producerFuture2.get();
            fail("should fail: conflicting producer name");
        } catch (Exception e) {
            // Expected
            assertTrue(e.getCause() instanceof UpgradeException);
            assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(),
                    HttpServletResponse.SC_CONFLICT);
        } finally {
            stopWebSocketClient(produceClient2);
        }
    } finally {
        stopWebSocketClient(produceClient1);
    }
}
 
Example #21
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 10000)
public void consumeMessagesInPartitionedTopicTest() throws Exception {
    final String namespace = "my-property/my-ns";
    final String topic = namespace + "/" + "my-topic7";
    admin.topics().createPartitionedTopic("persistent://" + topic, 3);

    final String subscription = "my-sub";
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/consumer/persistent/" + topic + "/" + subscription;
    final String producerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/producer/persistent/" + topic;

    URI consumeUri = URI.create(consumerUri);
    URI produceUri = URI.create(producerUri);

    WebSocketClient consumeClient = new WebSocketClient();
    WebSocketClient produceClient = new WebSocketClient();

    SimpleConsumerSocket consumeSocket = new SimpleConsumerSocket();
    SimpleProducerSocket produceSocket = new SimpleProducerSocket();

    try {
        produceClient.start();
        ClientUpgradeRequest produceRequest = new ClientUpgradeRequest();
        Future<Session> producerFuture = produceClient.connect(produceSocket, produceUri, produceRequest);
        producerFuture.get();
        produceSocket.sendMessage(100);
    } finally {
        stopWebSocketClient(produceClient);
    }

    Thread.sleep(500);

    try {
        consumeClient.start();
        ClientUpgradeRequest consumeRequest = new ClientUpgradeRequest();
        Future<Session> consumerFuture = consumeClient.connect(consumeSocket, consumeUri, consumeRequest);
        consumerFuture.get();
    } finally {
        stopWebSocketClient(consumeClient);
    }
}
 
Example #22
Source File: ServiceSocket.java    From JMeter-WebSocketSampler with Apache License 2.0 5 votes vote down vote up
public ServiceSocket(WebSocketSampler parent, WebSocketClient client) {
    this.parent = parent;
    this.client = client;
    
    //Evaluate response matching patterns in case thay contain JMeter variables (i.e. ${var})
    responsePattern = new CompoundVariable(parent.getResponsePattern()).execute();
    disconnectPattern = new CompoundVariable(parent.getCloseConncectionPattern()).execute();
    logMessage.append("\n\n[Execution Flow]\n");
    logMessage.append(" - Opening new connection\n");
    initializePatterns();
}
 
Example #23
Source File: MaxWsConnectionsTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {

  List<Session> clients = new ArrayList<>();

  while (true) {

    URI wsUri = new URI("ws", null, "localhost", Integer.parseInt(getPort()), "/jsonrpc", null,
        null);

    WebSocketClient jettyClient = new WebSocketClient(new SslContextFactory(true));
    jettyClient.start();
    Session session = jettyClient
        .connect(new WebSocketClientSocket(), wsUri, new ClientUpgradeRequest()).get();

    clients.add(session);

    log.debug("WebSocket client {} connected", clients.size());

    Thread.sleep(100);

    if (!session.isOpen()) {
      if (clients.size() < MAX_WS_CONNECTIONS) {
        fail("WebSocket num " + clients.size() + " disconnected. MAX_WS_CONNECTION="
            + MAX_WS_CONNECTIONS);
      } else {
        log.debug("WebSocket client {} disconnected from server", clients.size());
        break;
      }
    } else {

      if (clients.size() > MAX_WS_CONNECTIONS) {
        fail("Server should close automatically WebSocket connection above " + MAX_WS_CONNECTIONS
            + " but it has " + clients.size() + " open connections");
      }
    }
  }

}
 
Example #24
Source File: WebClientFactoryImplTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGetClients() throws Exception {
    HttpClient httpClient = webClientFactory.getCommonHttpClient();
    WebSocketClient webSocketClient = webClientFactory.getCommonWebSocketClient();

    assertThat(httpClient, is(notNullValue()));
    assertThat(webSocketClient, is(notNullValue()));
}
 
Example #25
Source File: RosBridge.java    From java_rosbridge with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Connects to the Rosbridge host at the provided URI.
 * @param rosBridgeURI the URI to the ROS Bridge websocket server. Note that ROS Bridge by default uses port 9090. An example URI is: ws://localhost:9090
 */
public void connect(String rosBridgeURI){
	WebSocketClient client = new WebSocketClient();
	try {
		client.start();
		URI echoUri = new URI(rosBridgeURI);
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		client.connect(this, echoUri, request);
		System.out.printf("Connecting to : %s%n", echoUri);

	} catch (Throwable t) {
		t.printStackTrace();
	}
}
 
Example #26
Source File: ZeppelinClient.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private WebSocketClient createNewWebsocketClient() {
  SslContextFactory sslContextFactory = new SslContextFactory();
  WebSocketClient client = new WebSocketClient(sslContextFactory);
  client.setMaxIdleTimeout(5 * MIN * 1000);
  client.setMaxTextMessageBufferSize(Client.getMaxNoteSize());
  client.getPolicy().setMaxTextMessageSize(Client.getMaxNoteSize());
  //TODO(khalid): other client settings
  return client;
}
 
Example #27
Source File: Demo_JettyWebSocketClient.java    From haxademic with MIT License 5 votes vote down vote up
protected void firstFrame() {
        try {
        	// web socket
        	HttpClient http = new HttpClient();
        	http.start();
            WebSocketClient websocket = new WebSocketClient(http);
            websocket.start();
        	try {

        		URI uri = new URI("ws://localhost:8787/websocket");
        		P.out("Connecting to: {}...", uri);
        		Session session = websocket.connect(new ToUpper356ClientSocket(), uri, new ClientUpgradeRequest()).get();
        		P.out("Connected to: {}", uri);
        		remote = session.getRemote();
        		remote.sendString("Hello World");
        	} catch (Exception e) {
        		throw new RuntimeIOException(e);
        	}
        	
//        	ClientUpgradeRequest request = new ClientUpgradeRequest();
//        	
//        	HttpClient http = new HttpClient();
//        	http.start();
//            WebSocketClient websocket = new WebSocketClient(http);
//            websocket.start();
//            try
//            {
//                String dest = "ws://localhost:8787/";
//                websocket.connect(new ToUpper356ClientSocket(), new URI(dest), request);
//            }
//            finally
//            {
//                websocket.stop();
//            } 
        } catch (Throwable t) {
            t.printStackTrace();
        }

	}
 
Example #28
Source File: WebsocketAppenderTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    // install decanter
    System.out.println(executeCommand("feature:repo-add decanter " + System.getProperty("decanter.version")));
    System.out.println(executeCommand("feature:install decanter-appender-websocket-servlet", new RolePrincipal("admin")));

    String httpList = executeCommand("http:list");
    while (!httpList.contains("Deployed")) {
        Thread.sleep(500);
        httpList = executeCommand("http:list");
    }
    System.out.println(httpList);

    // websocket
    WebSocketClient client = new WebSocketClient();
    DecanterSocket decanterSocket = new DecanterSocket();
    client.start();
    URI uri = new URI("ws://localhost:" + getHttpPort() + "/decanter-websocket");
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    client.connect(decanterSocket, uri, request).get();

    // sending event
    EventAdmin eventAdmin = getOsgiService(EventAdmin.class);
    HashMap<String, String> data = new HashMap<>();
    data.put("foo", "bar");
    Event event = new Event("decanter/collect/test", data);
    eventAdmin.sendEvent(event);

    decanterSocket.awaitClose(20, TimeUnit.SECONDS);

    Assert.assertEquals(1, decanterSocket.messages.size());

    Assert.assertTrue(decanterSocket.messages.get(0).contains("\"foo\":\"bar\""));
    Assert.assertTrue(decanterSocket.messages.get(0).contains("\"event_topics\":\"decanter/collect/test\""));

    client.stop();
}
 
Example #29
Source File: PerformanceTest.java    From nextrtc-signaling-server with MIT License 5 votes vote down vote up
private <T> Tuple<T> openSession(T socket) {
    WebSocketClient client = new WebSocketClient();
    try {
        client.start();
        client.connect(socket, uri);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return new Tuple<>(client, socket);
}
 
Example #30
Source File: WebSocketRunnerMock.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
@SneakyThrows
private void start(String server, String userName, String code)  {
    wsClient = new WebSocketClient();
    wsClient.start();

    URI uri = new URI(server + "?user=" + userName + "&code=" + code);
    System.out.println("Connecting to: " + uri);
    session = wsClient.connect(new ClientSocket(), uri).get(5000, TimeUnit.MILLISECONDS);
}