List of usage examples for io.vertx.core.http HttpServer websocketHandler
@Fluent HttpServer websocketHandler(Handler<ServerWebSocket> handler);
From source file:eu.rethink.mn.WebSocketServer.java
License:Apache License
public static void init(HttpServer server, Pipeline pipeline) { server.websocketHandler(ws -> { if (!ws.uri().equals("/ws")) { ws.reject();/*from w ww . j a v a 2 s . c o m*/ logger.info("RESOURCE-OPEN-REJECTED"); return; } final StringBuilder sb = new StringBuilder(); logger.info("RESOURCE-OPEN"); final PipeResource resource = pipeline.createResource(ws.textHandlerID(), close -> ws.close(), reply -> ws.writeFinalTextFrame(reply)); ws.frameHandler(frame -> { sb.append(frame.textData()); if (frame.isFinal()) { resource.processMessage(new PipeMessage(sb.toString())); sb.setLength(0); } }); ws.closeHandler(handler -> { logger.info("RESOURCE-CLOSE"); }); }); }
From source file:examples.HTTPExamples.java
License:Open Source License
public void example51(HttpServer server) { server.websocketHandler(websocket -> { System.out.println("Connected!"); }); }
From source file:examples.HTTPExamples.java
License:Open Source License
public void example52(HttpServer server) { server.websocketHandler(websocket -> { if (websocket.path().equals("/myapi")) { websocket.reject();/*from www . j a v a 2 s . co m*/ } else { // Do something } }); }
From source file:hu.elte.ik.robotika.futar.vertx.backend.verticle.HTTPVerticle.java
@Override public void start() { init();/*from w w w . j ava2 s . c om*/ HttpServer http = vertx.createHttpServer(); Router router = Router.router(vertx); // Setup websocket connection handling router.route("/eventbus/*").handler(eventBusHandler()); router.route("/ws").handler(this::handleWebSocketConnection); // Handle robot position data router.route("/api/robotposition/:data").handler(this::handleRobotPositionData); // Setup http session auth handling router.route().handler(CookieHandler.create()); router.route().handler(BodyHandler.create()); router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx))); // Simple auth service which uses a properties file for user/role info AuthProvider authProvider = ShiroAuth.create(vertx, ShiroAuthRealmType.PROPERTIES, new JsonObject()); // We need a user session handler too to make sure the user is stored in // the session between requests router.route().handler(UserSessionHandler.create(authProvider)); // Any requests to URI starting '/rest/' require login router.route("/rest/*").handler(SimpleAuthHandler.create(authProvider)); // Serve the static private pages from directory 'rest' // user/getAll TEST page router.route("/rest/user/getAll").handler(this::getAllUser); // Preload router.route("/rest/info").handler(this::getInfo); router.route("/loginhandler").handler(SimpleLoginHandler.create(authProvider)); router.route("/logout").handler(context -> { context.clearUser(); // Status OK context.response().setStatusCode(HttpStatus.SC_OK).end(); }); router.route().handler(StaticHandler.create().setWebRoot(webRoot)); http.websocketHandler(ws -> { String id = java.util.UUID.randomUUID().toString(); ws.handler(buffer -> { try { JsonObject response = new JsonObject(buffer.toString()); if (response.getString("action") != null && response.getString("action").equals("login.robot") && sockets.get(id) == null) { log.info("robot logged in:" + id); sockets.put(id, ws); JsonObject pb = new JsonObject(); pb.put("robotId", id); vertx.eventBus().publish("new.robot", Json.encode(pb)); } else if (response.getString("action") != null && response.getString("action").equals("found.bluetooth")) { log.info("found.bluetooth"); JsonObject pb = response.getJsonObject("data"); if (placedBTDevices.get(pb.getString("address")) == null && newBTDevices.get(pb.getString("address")) == null) { JsonObject data = new JsonObject(Json.encode(pb)); data.remove("rssi"); newBTDevices.put(pb.getString("address"), data); log.info("New bt device: " + buffer); vertx.eventBus().publish("new.bt.device", Json.encode(data)); } btData.get(id).remove(pb.getString("address")); log.info("Update bt data: " + id + " " + pb.getString("address") + " " + pb.getInteger("rssi")); double x = (pb.getInteger("rssi") - (-40.0)) / ((-10.0) * 2.0); log.info("sub calc res: " + x); double d = Math.pow(10.0, x); //RSSI (dBm) = -10n log10(d) + A log.info("the calculated distance is around: " + d + "m"); btData.get(id).put(pb.getString("address"), d * 27); } else if (response.getString("action") != null && response.getString("action").equals("start.bluetooth.scan")) { log.info("start.bluetooth.scan"); btData.remove(id); btData.put(id, new LinkedHashMap<String, Double>()); } else if (response.getString("action") != null && response.getString("action").equals("finished.bluetooth.scan")) { log.info("finished.bluetooth.scan"); if (btData.get(id).size() >= 3) { double x0 = 0, y0 = 0, r0 = 0, x1 = 0, y1 = 0, r1 = 0, x2 = 0, y2 = 0, r2 = 0; int i = 0; for (Map.Entry<String, Double> entry : btData.get(id).entrySet()) { String key = entry.getKey(); JsonObject placedBT = placedBTDevices.get(key); if (placedBT == null) { log.info("placedBT is null, the key was: " + key); continue; } double value = entry.getValue(); if (i == 0) { x0 = placedBT.getDouble("x"); y0 = placedBT.getDouble("y"); r0 = value; log.info("fill first circle x: " + x0 + " y: " + y0 + " r: " + r0); } else if (i == 1) { x1 = placedBT.getDouble("x"); y1 = placedBT.getDouble("y"); r1 = value; log.info("fill second circle x: " + x1 + " y: " + y1 + " r: " + r1); } else if (i == 2) { x2 = placedBT.getDouble("x"); y2 = placedBT.getDouble("y"); r2 = value; log.info("fill third circle x: " + x2 + " y: " + y2 + " r: " + r2); } else { break; } i++; } if (i == 3) { log.info("start calculation"); if (calculateThreeCircleIntersection(x0, y0, r0, x1, y1, r1, x2, y2, r2, id)) { log.info("solved circle intersection"); } else { log.info("cannot solve circle interseciton"); } } else { log.info("there was not enough BT device: " + i); } } else { log.info("There is not enough BT data to calculate the location of the robot."); } } log.info("got the following message from " + id + ": " + Json.encode(response)); } catch (Exception e) { log.info("Cannot process the following buffer: " + buffer); log.error(e); } }); ws.endHandler(e -> { JsonObject response = new JsonObject(); response.put("robotId", id); vertx.eventBus().publish("logout.robot", Json.encode(response)); sockets.remove(id); positionedRobots.remove(id); btData.remove(id); log.info("The following robot logged out: " + id); }); }).requestHandler(router::accept).listen(Integer.getInteger("http.port"), System.getProperty("http.address", "0.0.0.0")); }
From source file:io.sqp.proxy.ServerVerticle.java
License:Open Source License
@Override public void start() { // TODO: set subprotocols JsonObject config = config();//from w w w .j av a 2 s . co m String path = config.getString("path", DEFAULT_PATH); int port = config.getInteger("port", DEFAULT_PORT); int poolSize = config.getInteger("connectionPoolSize", DEFAULT_POOL_SIZE); JsonArray backendConfs = config.getJsonArray("backends"); _executorService = Executors.newFixedThreadPool(10); // TODO: set this reasonably // Initialize the backend connection pool BackendConnectionPool connectionPool = new VertxBackendConnectionPool(vertx, poolSize, backendConfs); try { connectionPool.init(); } catch (ServerErrorException e) { _logger.log(Level.SEVERE, "Failed to create the connection pool", e); throw new RuntimeException(e.getMessage(), e.getCause()); } HttpServerOptions options = new HttpServerOptions(); int maxFrameSize = options.getMaxWebsocketFrameSize(); // Create the actual server HttpServer server = vertx.createHttpServer(options); // For each incoming websocket connection: create a client connection object server.websocketHandler(socket -> { if (!socket.path().equals(path)) { socket.reject(); return; } // TODO: check sub protocols new VertxClientConnection(_executorService, socket, connectionPool, maxFrameSize); }); // start to listen server.listen(port, result -> { if (result.succeeded()) { _logger.log(Level.INFO, "Listening on port " + port + " and path '" + path + "'..."); setStarted(true); } else { _logger.log(Level.SEVERE, "Failed to listen", result.cause()); setStartingError(result.cause()); } }); }