Example usage for javax.websocket WebSocketContainer connectToServer

List of usage examples for javax.websocket WebSocketContainer connectToServer

Introduction

In this page you can find the example usage for javax.websocket WebSocketContainer connectToServer.

Prototype

Session connectToServer(Class<?> annotatedEndpointClass, URI path) throws DeploymentException, IOException;

Source Link

Usage

From source file:dk.dma.navnet.server.AbstractServerConnectionTest.java

protected TesstEndpoint newClient() throws Exception {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    TesstEndpoint t = new TesstEndpoint();
    container.connectToServer(t, new URI("ws://localhost:" + clientPort));
    allClient.add(t);// w  w w  .  jav  a2  s . c om
    return t;
}

From source file:eu.agilejava.snoop.scan.SnoopClient.java

/**
 * Sends message to the WebSocket server.
 *
 * @param endpoint The server endpoint//from   w ww .j  ava 2s. co m
 * @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;
}

From source file:org.sample.client.TestRemoteClient.java

/**
 * Processes requests for both HTTP//from   w  ww .  java2s.c om
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet TestRemoteClient</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet TestRemoteClient at " + request.getContextPath() + "</h1>");

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = "ws://echo.websocket.org:80/";
        out.println("Connecting to " + uri);
        container.connectToServer(MyClient.class, URI.create(uri));
        out.println("<br><br>Look in server.log for log messages from message exchange between client/server.");

        out.println("</body>");
        out.println("</html>");
    } catch (DeploymentException ex) {
        Logger.getLogger(TestRemoteClient.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:org.sample.client.TestLocalClient.java

/**
 * Processes requests for both HTTP//from   w ww . j ava  2  s. co m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet TestServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = "ws://localhost:8080" + request.getContextPath() + "/websocket";
        out.println("Connecting to " + uri);
        container.connectToServer(MyClient.class, URI.create(uri));
        out.println("<br><br>Look in server.log for log messages from message exchange between client/server.");

        out.println("</body>");
        out.println("</html>");
    } catch (DeploymentException ex) {
        Logger.getLogger(TestLocalClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.hadoop.gateway.websockets.BadUrlTest.java

/**
 * Test websocket proxying through gateway.
 *
 * @throws Exception//from w  ww.j a v a 2 s.  c  o  m
 */

@Test
public void testBadUrl() throws Exception {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    WebsocketClient client = new WebsocketClient();

    container.connectToServer(client, new URI(serverUri.toString() + "gateway/websocket/ws"));

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

    Assert.assertThat(client.close.getCloseCode().getCode(),
            CoreMatchers.is(CloseReason.CloseCodes.UNEXPECTED_CONDITION.getCode()));

}

From source file:org.apache.hadoop.gateway.websockets.WebsocketEchoTest.java

/**
 * Test direct connection to websocket server without gateway
 * /*from   www  . j ava  2s  .  c  om*/
 * @throws Exception
 */
@Test
public void testDirectEcho() throws Exception {

    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    WebsocketClient client = new WebsocketClient();

    Session session = container.connectToServer(client, backendServerUri);

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

}

From source file:org.apache.hadoop.gateway.websockets.WebsocketEchoTest.java

/**
 * Test websocket proxying through gateway.
 * //from   w  ww.  j ava2s .  c o m
 * @throws Exception
 */
@Test
public void testGatewayEcho() throws Exception {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    WebsocketClient client = new WebsocketClient();
    Session session = container.connectToServer(client, new URI(serverUri.toString() + "gateway/websocket/ws"));

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

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

}

From source file:org.apache.hadoop.gateway.websockets.WebsocketMultipleConnectionTest.java

/**
 * Test websocket proxying through gateway.
 * // ww  w  .j ava 2  s  . com
 * @throws Exception
 */
@Test
public void testMultipleConnections() throws Exception {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    final CountDownLatch latch = new CountDownLatch(MAX_CONNECTIONS);

    Session[] sessions = new Session[MAX_CONNECTIONS];

    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

    System.gc();
    final long heapt1 = memoryMXBean.getHeapMemoryUsage().getUsed();
    final long nonHeapt1 = memoryMXBean.getNonHeapMemoryUsage().getUsed();

    for (int i = 0; i < MAX_CONNECTIONS; i++) {

        sessions[i] = container.connectToServer(new WebsocketClient() {

            @Override
            public void onMessage(String message) {
                latch.countDown();

            }

        }, new URI(serverUri.toString() + "gateway/websocket/ws"));

    }

    for (int i = 0; i < MAX_CONNECTIONS; i++) {
        /* make sure the session is active and valid before trying to connect */
        if (sessions[i].isOpen() && sessions[i].getBasicRemote() != null) {
            sessions[i].getBasicRemote().sendText("OK");
        }
    }

    latch.await(5 * MAX_CONNECTIONS, TimeUnit.MILLISECONDS);

    System.gc();

    final long heapUsed = memoryMXBean.getHeapMemoryUsage().getUsed() - heapt1;
    final long nonHeapUsed = memoryMXBean.getNonHeapMemoryUsage().getUsed() - nonHeapt1;

    System.out.println("heapUsed = " + heapUsed);
    System.out.println("nonHeapUsed = " + nonHeapUsed);

    /* 90 KB per connection */
    /*
    long expected = 90 * 1024 * MAX_CONNECTIONS;
    assertThat("heap used", heapUsed, lessThan(expected));
    */
}

From source file:org.wso2.carbon.device.mgt.analytics.wsproxy.outbound.AnalyticsClient.java

/**
 * Create {@link AnalyticsClient} instance.
 *//*from  w ww .j  av  a 2s  .c  o  m*/
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);
    }
}

From source file:org.wso2.carbon.integration.test.client.WebSocketClient.java

public void send(String url, String message) {
    receivedMessage = null;//from  w  w  w  .  j av  a  2s  .c o  m
    URI uri = URI.create(url);

    try {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try {
            // Attempt Connect
            Session session = container.connectToServer(EventSocketClient.class, uri);
            // Send a message
            session.getBasicRemote().sendText(message);
            // Close session
            session.close();
        } finally {
            // Force lifecycle stop when done with container.
            // This is to free up threads and resources that the
            // JSR-356 container allocates. But unfortunately
            // the JSR-356 spec does not handle lifecycles (yet)
            if (container instanceof LifeCycle) {
                ((LifeCycle) container).stop();
            }
        }
    } catch (Throwable t) {
        log.error(t);
    }
}