javax.websocket.WebSocketContainer Java Examples

The following examples show how to use javax.websocket.WebSocketContainer. 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 Project: tomcatsrc   Author: wangyingjie   File: TestWsRemoteEndpointImplServer.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClientDropsConnection() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug58624Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    SimpleClient client = new SimpleClient();
    URI uri = new URI("ws://localhost:" + getPort() + Bug58624Config.PATH);

    Session session = wsContainer.connectToServer(client, uri);
    // Break point A required on following line
    session.close();
}
 
Example #2
Source Project: Tomcat7.0.67   Author: tryandcatch   File: TestWebSocketFrameClient.java    License: Apache License 2.0 6 votes vote down vote up
public void echoTester(String path) throws Exception {
    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    ClientEndpointConfig clientEndpointConfig =
            ClientEndpointConfig.Builder.create().build();
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientEndpointConfig,
            new URI("ws://localhost:" + getPort() + path));
    CountDownLatch latch =
            new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText("Hello");

    handler.getLatch().await(100, TimeUnit.MILLISECONDS);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    for (String message : messages) {
        Assert.assertEquals("Hello", message);
    }
    wsSession.close();
}
 
Example #3
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: TestConnectionLimit.java    License: MIT License 6 votes vote down vote up
@Override
public void run() {
    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    int count = 0;

    try {
        while (true) {
            wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
                    Builder.create().build(), uri);
            count = counter.incrementAndGet();
            if (count % 100 == 0) {
                System.out.println(count + " and counting...");
            }
        }
    } catch (IOException | DeploymentException ioe) {
        // Let thread die
    }
}
 
Example #4
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: TestWsWebSocketContainer.java    License: MIT License 6 votes vote down vote up
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointInvalidScheme() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ftp://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
}
 
Example #5
Source Project: rogue-cloud   Author: codewind-resources   File: LibertySessionWrapper.java    License: Apache License 2.0 6 votes vote down vote up
private void connect(String url) {
	// Don't try to connect if we have already disposed of the session, or the client instance
	if (disposed || LibertyClientInstance.getInstance().isDisposed()) {
		log.interesting("Ignoring connect as instance of wrapper is disposed ["+disposed+","+LibertyClientInstance.getInstance().isDisposed()+"]", parent.getLogContext());
		return;
	}

	log.interesting("Attempting to connect", parent.getLogContext());
	final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
	//
	// ClientManager client = ClientManager.createClient();

	WebSocketContainer c = ContainerProvider.getWebSocketContainer();
	c.setDefaultMaxTextMessageBufferSize(1024 * 1024);
	c.setDefaultMaxSessionIdleTimeout(2 * TimeUnit.MILLISECONDS.convert(RCSharedConstants.MAX_ROUND_LENGTH_IN_NANOS, TimeUnit.NANOSECONDS));
	try {
		c.connectToServer(this.hce, cec, new URI(url));
		// Wait for the endpoint to call us on success or failure.
	} catch (DeploymentException | IOException | URISyntaxException e) {
		errorOccurred(null);
	}

}
 
Example #6
Source Project: knox   Author: apache   File: BadBackendTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(timeout = 8000)
public void testBadBackEnd() throws IOException, Exception {
  final String message = "Echo";

  WebSocketContainer container = ContainerProvider.getWebSocketContainer();

  WebsocketClient client = new WebsocketClient();
  javax.websocket.Session session = container.connectToServer(client,
      proxyUri);
  session.getBasicRemote().sendText(message);

  client.awaitClose(CloseReason.CloseCodes.UNEXPECTED_CONDITION.getCode(), 1000,
      TimeUnit.MILLISECONDS);

  Assert.assertThat(client.close.getCloseCode().getCode(), CoreMatchers.is(CloseReason.CloseCodes.UNEXPECTED_CONDITION.getCode()));
}
 
Example #7
Source Project: Tomcat7.0.67   Author: tryandcatch   File: TestWsRemoteEndpointImplServer.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClientDropsConnection() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug58624Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    SimpleClient client = new SimpleClient();
    URI uri = new URI("ws://localhost:" + getPort() + Bug58624Config.PATH);

    Session session = wsContainer.connectToServer(client, uri);
    // Break point A required on following line
    session.close();
}
 
Example #8
Source Project: ZStreamingQuote   Author: instruritesh   File: WebsocketClientEndpoint.java    License: MIT License 6 votes vote down vote up
/**
 * constructor
 * 
 * @param endpointURI
 */
public WebsocketClientEndpoint(URI endpointURI, IwsSessionNotifier sessionNotifier) {
	try {
		this.sessionNotifier = sessionNotifier;
		System.out.println("WebsocketClientEndpoint.WebsocketClientEndpoint(): creating WebSocketContainer...");
		WebSocketContainer container = ContainerProvider.getWebSocketContainer();
		container.connectToServer(this, endpointURI);
	} catch (Exception e) {
		System.out.println(
				"WebsocketClientEndpoint.WebsocketClientEndpoint(): ERROR: Exception on container connectToServer, reason: "
						+ e.getMessage());
		//throw new RuntimeException(e);
       	//notify initiate failed
       	this.sessionNotifier.notifyWsInitiateFailed();
	}
}
 
Example #9
Source Project: wildfly-samples   Author: arun-gupta   File: AnnotatedServerTest.java    License: MIT License 6 votes vote down vote up
@Test
    public void testEndpoint() throws IOException, ServletException, DeploymentException, InterruptedException {
        AnnotatedWebSocketServer server = new AnnotatedWebSocketServer();
        server.start();

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = "ws://localhost:8080/server";
        System.out.println("Connecting to " + uri);
        container.connectToServer(MyClient.class, URI.create(uri));

//        WebClient webClient = new WebClient();
//        TextPage page = webClient.getPage("http://localhost:8080/myapp/server");
//        assertEquals("Hello World", page.getContent());
        assertTrue(AnnotatedWebSocketServer.LATCH.await(3, TimeUnit.SECONDS));
        server.stop();
    }
 
Example #10
Source Project: spring-analysis-note   Author: Vip-Augus   File: AbstractTyrusRequestUpgradeStrategy.java    License: MIT License 6 votes vote down vote up
private Object createEndpoint(ServerEndpointRegistration registration, ComponentProviderService provider,
		WebSocketContainer container, TyrusWebSocketEngine engine) throws DeploymentException {

	DirectFieldAccessor accessor = new DirectFieldAccessor(engine);
	Object sessionListener = accessor.getPropertyValue("sessionListener");
	Object clusterContext = accessor.getPropertyValue("clusterContext");
	try {
		if (constructorWithBooleanArgument) {
			// Tyrus 1.11+
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null, Boolean.TRUE);
		}
		else {
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null);
		}
	}
	catch (Exception ex) {
		throw new HandshakeFailureException("Failed to register " + registration, ex);
	}
}
 
Example #11
Source Project: snoop   Author: ivargrimstad   File: SnoopRegistrationClient.java    License: MIT License 6 votes vote down vote up
/**
 * Sends message to the WebSocket server.
 *
 * @param endpoint The server endpoint
 * @param msg The message
 * @return a return message
 */
private String sendMessage(String endpoint, String msg) {

    LOGGER.config(() -> "Sending message: " + msg);

    String returnValue = "-1";
    try {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = serviceUrl + endpoint;
        Session session = container.connectToServer(this, URI.create(uri));
        session.getBasicRemote().sendText(msg != null ? msg : "");
        returnValue = session.getId();

    } catch (DeploymentException | IOException ex) {
        LOGGER.warning(ex.getMessage());
    }

    return returnValue;
}
 
Example #12
Source Project: knox   Author: apache   File: MessageFailureTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(timeout = 8000)
public void testMessageTooBig() throws Exception {
  final String bigMessage = RandomStringUtils.randomAscii(66001);

  WebSocketContainer container = ContainerProvider.getWebSocketContainer();

  WebsocketClient client = new WebsocketClient();
  javax.websocket.Session session = container.connectToServer(client,
      proxyUri);
  session.getBasicRemote().sendText(bigMessage);

  client.awaitClose(CloseReason.CloseCodes.TOO_BIG.getCode(), 1000,
      TimeUnit.MILLISECONDS);

  Assert.assertThat(client.close.getCloseCode().getCode(), CoreMatchers.is(CloseReason.CloseCodes.TOO_BIG.getCode()));
}
 
Example #13
Source Project: pentaho-kettle   Author: pentaho   File: DaemonMessagesClientEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
public DaemonMessagesClientEndpoint( String host, int port, boolean ssl,
                                     MessageEventService messageEventService ) throws KettleException {
  try {
    setAuthProperties();

    String url = String.format( URL_TEMPLATE, ( ssl ? PRFX_WS_SSL : PRFX_WS ), host, port );
    URI uri = new URI( url );
    this.messageEventService = messageEventService;

    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    container.connectToServer( this, ClientEndpointConfig.Builder.create()
      .encoders( Collections.singletonList( MessageEncoder.class ) )
      .decoders( Collections.singletonList( MessageDecoder.class ) )
      .configurator( new SessionConfigurator( uri, keytab, principal ) )
      .build(), uri );

  } catch ( Exception e ) {
    throw new KettleException( e );
  }
}
 
Example #14
Source Project: spring4-understanding   Author: langtianya   File: AbstractTyrusRequestUpgradeStrategy.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object createdEndpoint(ServerEndpointRegistration registration, ComponentProviderService provider,
		WebSocketContainer container, TyrusWebSocketEngine engine) throws DeploymentException {

	DirectFieldAccessor accessor = new DirectFieldAccessor(engine);
	Object sessionListener = accessor.getPropertyValue("sessionListener");
	Object clusterContext = accessor.getPropertyValue("clusterContext");
	try {
		if (constructorWithBooleanArgument) {
			// Tyrus 1.11+
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null, Boolean.TRUE);
		}
		else {
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null);
		}
	}
	catch (Exception ex) {
		throw new HandshakeFailureException("Failed to register " + registration, ex);
	}
}
 
Example #15
Source Project: jetty-web-sockets-jsr356   Author: reta   File: ClientStarter.java    License: Apache License 2.0 6 votes vote down vote up
public static void main( final String[] args ) throws Exception {
	final String client = UUID.randomUUID().toString().substring( 0, 8 );
	
	final WebSocketContainer container = ContainerProvider.getWebSocketContainer();				
	final String uri = "ws://localhost:8080/broadcast";		
	
	try( Session session = container.connectToServer( BroadcastClientEndpoint.class, URI.create( uri ) ) ) {
		for( int i = 1; i <= 10; ++i ) {
			session.getBasicRemote().sendObject( new Message( client, "Message #" + i ) );
			Thread.sleep( 1000 );
		}
	}
	
	// JSR-356 has no concept of Container lifecycle.
	// (This is an oversight on the spec's part)
	// This stops the lifecycle of the Client WebSocketContainer
	if( container instanceof LifeCycle ) {
	    ( ( LifeCycle )container ).stop();
	}
}
 
Example #16
Source Project: java-technology-stack   Author: codeEngraver   File: AbstractTyrusRequestUpgradeStrategy.java    License: MIT License 6 votes vote down vote up
private Object createEndpoint(ServerEndpointRegistration registration, ComponentProviderService provider,
		WebSocketContainer container, TyrusWebSocketEngine engine) throws DeploymentException {

	DirectFieldAccessor accessor = new DirectFieldAccessor(engine);
	Object sessionListener = accessor.getPropertyValue("sessionListener");
	Object clusterContext = accessor.getPropertyValue("clusterContext");
	try {
		if (constructorWithBooleanArgument) {
			// Tyrus 1.11+
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null, Boolean.TRUE);
		}
		else {
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null);
		}
	}
	catch (Exception ex) {
		throw new HandshakeFailureException("Failed to register " + registration, ex);
	}
}
 
Example #17
Source Project: quarks   Author: quarks-edge   File: WebSocketClientConnector.java    License: Apache License 2.0 5 votes vote down vote up
public WebSocketClientConnector(Properties config, Supplier<WebSocketContainer> containerFn) {
    Objects.requireNonNull(config, "config");
    this.config = config;
    checkConfig();
    this.containerFn = containerFn!=null
            ? containerFn
            : () -> getWebSocketContainer();
}
 
Example #18
Source Project: tomcatsrc   Author: wangyingjie   File: TestWsWebSocketContainer.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointNoHost() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC));
}
 
Example #19
Source Project: websocket-classloader   Author: kawasima   File: WebSocketClassLoader.java    License: Apache License 2.0 5 votes vote down vote up
public WebSocketClassLoader(String url, ClassLoader parent)
        throws DeploymentException, IOException {
    super(parent);

    logger.debug("Parent classloader=" + parent);
    cacheDirectory = PropertyUtils.getFileSystemProperty("wscl.cache.directory");

    if (cacheDirectory != null && !cacheDirectory.exists() && !cacheDirectory.mkdirs()) {
        throw new IllegalArgumentException(
                "Can't create cache directory: " + cacheDirectory);
    }
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    endpoint = new ClassLoaderEndpoint();
    container.connectToServer(endpoint,
            ClientEndpointConfig.Builder.create().build(), URI.create(url));
    try {
        URL httpUrl = new URL(url.replaceFirst("ws://", "http://"));
        QueryStringDecoder decoder = new QueryStringDecoder(httpUrl.getQuery());
        List<String> classLoaderIds = decoder.parameters().get("classLoaderId");
        WebSocketURLStreamHandler urlStreamHandler = new WebSocketURLStreamHandler(endpoint, cacheDirectory);
        if (classLoaderIds !=  null && !classLoaderIds.isEmpty())
            urlStreamHandler.setClassLoaderId(classLoaderIds.get(0));

        baseUrl = new URL("ws", httpUrl.getHost(), httpUrl.getPort(),
                httpUrl.getFile(), urlStreamHandler);
    } catch (Exception e) {
        throw new RuntimeException("ClassProvider URL is invalid.", e);
    }
}
 
Example #20
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: TestPojoEndpointBase.java    License: MIT License 5 votes vote down vote up
@Test
public void testBug54716() throws Exception {
    TestUtil.generateMask();
    // Set up utility classes
    Bug54716 server = new Bug54716();
    SingletonConfigurator.setInstance(server);
    ServerConfigListener.setPojoClazz(Bug54716.class);

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ServerConfigListener.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();


    tomcat.start();

    Client client = new Client();
    URI uri = new URI("ws://localhost:" + getPort() + "/");

    wsContainer.connectToServer(client, uri);

    // Server should close the connection after the exception on open.
    boolean closed = client.waitForClose(5);
    Assert.assertTrue("Server failed to close connection", closed);
}
 
Example #21
Source Project: tomcatsrc   Author: wangyingjie   File: TestWsPingPongMessages.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPingPongMessages() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider
            .getWebSocketContainer();

    tomcat.start();

    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder
                    .create().build(), new URI("ws://localhost:"
                    + getPort() + TesterEchoServer.Config.PATH_ASYNC));

    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties()
            .get("endpoint");
    tep.setLatch(latch);

    PongMessageHandler handler = new PongMessageHandler(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendPing(applicationData);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    Assert.assertArrayEquals(applicationData.array(),
            (handler.getMessages().peek()).getApplicationData().array());
}
 
Example #22
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: TestWsServerContainer.java    License: MIT License 5 votes vote down vote up
@Test
public void testBug58232() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug54807Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Assert.assertEquals(LifecycleState.STARTED, ctx.getState());

    SimpleClient client = new SimpleClient();
    URI uri = new URI("ws://localhost:" + getPort() + "/echoBasic");

    try (Session session = wsContainer.connectToServer(client, uri);) {
        CountDownLatch latch = new CountDownLatch(1);
        BasicText handler = new BasicText(latch);
        session.addMessageHandler(handler);
        session.getBasicRemote().sendText("echoBasic");

        boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
        Assert.assertTrue(latchResult);

        Queue<String> messages = handler.getMessages();
        Assert.assertEquals(1, messages.size());
        for (String message : messages) {
            Assert.assertEquals("echoBasic", message);
        }
    }
}
 
Example #23
Source Project: tomcatsrc   Author: wangyingjie   File: TesterWsClientAutobahn.java    License: Apache License 2.0 5 votes vote down vote up
private static void executeTestCase(WebSocketContainer wsc, int testCase)
        throws Exception {
    URI uri = new URI("ws://" + HOST + ":" + PORT + "/runCase?case=" +
            testCase + "&agent=" + USER_AGENT);
    TestCaseClient testCaseClient = new TestCaseClient();
    wsc.connectToServer(testCaseClient, uri);
    testCaseClient.waitForClose();
}
 
Example #24
Source Project: carbon-device-mgt   Author: wso2   File: AnalyticsClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create {@link AnalyticsClient} instance.
 */
public AnalyticsClient(Session clientSession, URI endpointURI) throws WSProxyException {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    this.clientSession = clientSession;

    try {
        this.analyticsSession = container.connectToServer(this, endpointURI);
    } catch (DeploymentException | IOException e) {
        String msg = "Error occurred while connecting to remote endpoint " + endpointURI.toString();
        log.error(msg, e);
        throw new WSProxyException(msg, e);
    }
}
 
Example #25
Source Project: knox   Author: apache   File: MessageFailureTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(timeout = 8000)
public void testMessageOk() throws Exception {
  final String message = "Echo";

  WebSocketContainer container = ContainerProvider.getWebSocketContainer();

  WebsocketClient client = new WebsocketClient();
  javax.websocket.Session session = container.connectToServer(client,
      proxyUri);
  session.getBasicRemote().sendText(message);

  client.messageQueue.awaitMessages(1, 1000, TimeUnit.MILLISECONDS);

  Assert.assertThat(client.messageQueue.get(0), CoreMatchers.is("Echo"));
}
 
Example #26
Source Project: pnc   Author: project-ncl   File: WsUpdatesClient.java    License: Apache License 2.0 5 votes vote down vote up
public void subscribeBlocking(String topic, String filter, Consumer<String> onMessage)
        throws IOException, DeploymentException {

    ProgressUpdatesRequest progressUpdatesRequest = ProgressUpdatesRequest.subscribe(topic, filter);

    UpdatesMessageHandler updatesMessageHandler = new UpdatesMessageHandler(onMessage);

    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    String uri = "ws://localhost:8080/pnc-rest-new/" + NotificationsEndpoint.ENDPOINT_PATH;
    Session session = container.connectToServer(updatesMessageHandler, URI.create(uri));

    RemoteEndpoint.Basic asyncRemote = session.getBasicRemote();
    asyncRemote.sendText(toJson(progressUpdatesRequest));
}
 
Example #27
Source Project: openwebbeans-meecrowave   Author: apache   File: WSTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void run() throws InterruptedException, DeploymentException, IOException, URISyntaxException {
	CountDownLatch cdl = new CountDownLatch(5);
	WebSocketContainer container = ContainerProvider.getWebSocketContainer();
	String wsEndpoint = String.format("ws://localhost:%d/ws-chat", CONTAINER.getConfiguration().getHttpPort());
	Session session = container.connectToServer(new ChatClient(cdl), new URI(wsEndpoint));
	assertTrue(cdl.await(20, TimeUnit.SECONDS));
	session.close();

}
 
Example #28
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: TesterWsClientAutobahn.java    License: MIT License 5 votes vote down vote up
private static int getTestCaseCount(WebSocketContainer wsc)
        throws Exception {

    URI uri = new URI("ws://" + HOST + ":" + PORT + "/getCaseCount");
    CaseCountClient caseCountClient = new CaseCountClient();
    wsc.connectToServer(caseCountClient, uri);
    return caseCountClient.getCaseCount();
}
 
Example #29
Source Project: spring4-understanding   Author: langtianya   File: StandardWebSocketClientTests.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
	this.headers = new WebSocketHttpHeaders();
	this.wsHandler = new AbstractWebSocketHandler() {
	};
	this.wsContainer = mock(WebSocketContainer.class);
	this.wsClient = new StandardWebSocketClient(this.wsContainer);
}
 
Example #30
Source Project: knox   Author: apache   File: WebsocketServerInitiatedMessageTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGatewayServerInitiatedEcho() throws Exception {
  WebSocketContainer container = ContainerProvider.getWebSocketContainer();

  WebsocketClient client = new WebsocketClient();
  container.connectToServer(client,
          new URI(serverUri.toString() + "gateway/websocket/123foo456bar/channels"));

  //session.getBasicRemote().sendText("Echo");
  client.messageQueue.awaitMessages(1, 5000, TimeUnit.MILLISECONDS);

  assertThat(client.messageQueue.get(0), is("echo"));
}