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<? extends Endpoint> endpoint, ClientEndpointConfig clientEndpointConfiguration,
        URI path) throws DeploymentException, IOException;

Source Link

Document

Creates a new connection to the WebSocket.

Usage

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

/**
 * Processes requests for both HTTP//  ww w  .j a  va2 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>");

        List<Class<? extends Encoder>> encoders = new ArrayList<>();
        encoders.add(MyMessageEncoder.class);
        List<Class<? extends Decoder>> decoders = new ArrayList<>();
        decoders.add(MyMessageDecoder.class);

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

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

From source file:co.paralleluniverse.comsat.webactors.AbstractWebActorTest.java

@Test
public void testWebSocketMsg()
        throws IOException, InterruptedException, ExecutionException, DeploymentException {
    BasicCookieStore cookieStore = new BasicCookieStore();
    final HttpGet httpGet = new HttpGet("http://localhost:8080");
    HttpClients.custom().setDefaultRequestConfig(requestConfig).setDefaultCookieStore(cookieStore).build()
            .execute(httpGet, new BasicResponseHandler());

    final SettableFuture<String> res = new SettableFuture<>();
    final WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    wsContainer.setAsyncSendTimeout(timeout);
    wsContainer.setDefaultMaxSessionIdleTimeout(timeout);
    try (final Session ignored = wsContainer.connectToServer(sendAndGetTextEndPoint("test it", res),
            getClientEndPointConfig(cookieStore), URI.create("ws://localhost:8080/ws"))) {
        final String s = res.get();
        assertEquals("test it", s);
    }/* w w w .  java 2 s  .  c  om*/
}

From source file:com.raspoid.network.pushbullet.Pushbullet.java

/**
 * Constructor for a new Pushbullet instance with a specific access token, a device name
 * corresponding to the name that your robot will take in your Pushbullet list of devices,
 * and the Raspoid router to use with this Pushbullet instance.
 * //from w w  w .  j ava  2s .  co m
 * <p>The access token can easily be retrieved from your Pushbullet account settings.</p>
 * 
 * <p>Note that if a device with the specified name already exists, this device will be
 * retrieved. If no devices with this name exists, a new one will be created.</p>
 * 
 * <p>As for other types of servers, the router is used to deal with requests
 * received on this Pushbullet instance.</p>
 * 
 * @param accessToken the access token used to access Pushbullet services.
 * @param deviceName the name corresponding to your robot's Pushbullet device.
 * @param router the router to use to deal with requests received on the deviceName.
 */
public Pushbullet(String accessToken, String deviceName, Router router) {
    this.accessToken = accessToken;

    gson = new Gson();

    this.deviceIden = initDevice(deviceName);
    this.lastPushReceivedTime = initLastPushReceivedTime();

    // WebSocket
    final ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
    WebSocketContainer websocketClient = ContainerProvider.getWebSocketContainer();
    try {
        session = websocketClient.connectToServer(new PushbulletClientEndpoint(router), clientEndpointConfig,
                new URI("wss://stream.pushbullet.com/websocket/" + accessToken));
    } catch (DeploymentException | IOException | URISyntaxException e) {
        throw new RaspoidException("Error when connecting to Pushbullet server.", e);
    }

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Websocket closed by client"));
        } catch (IOException e) {
            throw new RaspoidException("Error when closing the websocket session with Pushbullet.", e);
        }
    }));
}

From source file:io.hosuaby.restful.simulators.TeapotSimulator.java

/**
 * Creates and starts teapot simulator.//from w ww  . j  a  va  2s  . c o m
 *
 * @param teapot    teapot domain object
 * @param port      port number of the server
 *
 * @throws URISyntaxException
 * @throws DeploymentException
 * @throws IOException
 */
public TeapotSimulator(Teapot teapot, int port) throws URISyntaxException, DeploymentException, IOException {

    /* Get websocket container */
    final WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    /* Configuration of teapot client endpoint */
    final ClientEndpointConfig teapotConfig = ClientEndpointConfig.Builder.create().build();

    /* Disable websocket timeout */
    container.setDefaultMaxSessionIdleTimeout(0);

    URI uri = new URI(String.format(REGISTER_URL, port, teapot.getId()));

    /* Create websocket client for the teapot */
    container.connectToServer(new TeapotSimulatorEndpoint(this), teapotConfig, uri);

    /* Create the file system */
    fs = new TeapotFs();

    /* Create help.txt file */
    fs.cat("help.txt", createHelpFileContent());

    /* Create license file */
    fs.cat("license", createLicenseFileContent());

    /* Create config.json file */
    fs.cat("config.json", createConfigFileContent(teapot));
}

From source file:org.ocelotds.integration.AbstractOcelotTest.java

/**
 * Create session/*from   w  w w.  j a v a 2 s. c om*/
 *
 * @param jsessionid
 * @param userpwd
 * @return
 */
protected Session createAndGetSession(String jsessionid, String userpwd) {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    try {
        StringBuilder sb = new StringBuilder("ws://localhost:");
        sb.append(PORT).append(Constants.SLASH).append(CTXPATH).append(Constants.SLASH)
                .append("ocelot-endpoint");
        URI uri = new URI(sb.toString());
        return container.connectToServer(new Endpoint() {
            @Override
            public void onOpen(Session session, EndpointConfig config) {
            }
        }, createClientEndpointConfigWithJsession(jsessionid, userpwd), uri);
    } catch (URISyntaxException | DeploymentException | IOException ex) {
        ex.getCause().printStackTrace();
        fail("CONNEXION FAILED " + ex.getMessage());
    }
    return null;
}

From source file:org.kurento.test.services.KmsService.java

private void waitForKms() {
    long initTime = System.nanoTime();

    @ClientEndpoint//from  w  w w  .  j a v  a2  s .c  om
    class WebSocketClient extends Endpoint {

        @OnClose
        @Override
        public void onClose(Session session, CloseReason closeReason) {
        }

        @OnOpen
        @Override
        public void onOpen(Session session, EndpointConfig config) {
        }
    }

    if (wsUri != null) {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();

        final int retries = 600;
        final int waitTime = 100;

        for (int i = 0; i < retries; i++) {
            try {
                log.debug("({}) Wait for KMS: {}. Container: {}", i, wsUri, container);
                Session wsSession = container.connectToServer(new WebSocketClient(),
                        ClientEndpointConfig.Builder.create().build(), new URI(wsUri));
                wsSession.close();

                double time = (System.nanoTime() - initTime) / (double) 1000000;

                log.debug("Connected to KMS in " + String.format("%3.2f", time) + " milliseconds");
                return;
            } catch (DeploymentException | IOException | URISyntaxException e) {
                try {
                    log.warn("Exception while waiting for KMS: {}. {}", wsUri, e.getMessage());
                    Thread.sleep(waitTime);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }

        throw new KurentoException("Timeout of " + retries * waitTime + " millis waiting for KMS " + wsUri);

    } else {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error("InterruptedException {}", e.getMessage());
        }
    }
}