io.vertx.core.http.ServerWebSocket Java Examples
The following examples show how to use
io.vertx.core.http.ServerWebSocket.
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: WebSocketHandler.java From andesite-node with MIT License | 6 votes |
FrameHandler(@Nonnull Andesite andesite, @Nonnull String user, @Nonnull ServerWebSocket ws, long connectionId, boolean lavalink) { this.andesite = andesite; this.user = user; this.ws = ws; this.connectionId = connectionId; this.lavalink = lavalink; this.context = andesite.vertx().getOrCreateContext(); if(lavalink) { this.timerId = andesite.vertx().setPeriodic(30_000, __ -> { var stats = andesite.requestHandler().nodeStatsForLavalink(); ws.writeFinalTextFrame(stats .put("op", "stats") .encode()); }); } else { this.timerId = null; } andesite.dispatcher().register(listener); ws.closeHandler(__ -> handleClose()); }
Example #2
Source File: WSLocalHandler.java From vert.x-microservice with Apache License 2.0 | 6 votes |
@Override public void findRouteSocketInRegistryAndRemove(ServerWebSocket serverSocket) { final SharedData sharedData = this.vertx.sharedData(); final String binaryHandlerID = serverSocket.binaryHandlerID(); final String textHandlerID = serverSocket.textHandlerID(); final LocalMap<String, byte[]> wsRegistry = sharedData.getLocalMap(WS_REGISTRY); final WSEndpointHolder holder = getWSEndpointHolderFromSharedData(wsRegistry); if (holder != null) { final List<WSEndpoint> all = holder.getAll(); final Optional<WSEndpoint> first = all.parallelStream().filter(e -> e.getBinaryHandlerId().equals(binaryHandlerID) && e.getTextHandlerId().equals(textHandlerID)).findFirst(); first.ifPresent(endpoint -> { holder.remove(endpoint); wsRegistry.replace(WS_ENDPOINT_HOLDER, serialize(holder)); log("OK REMOVE: " + serverSocket.binaryHandlerID()); }); } }
Example #3
Source File: WebSocketHandler.java From wisdom with Apache License 2.0 | 6 votes |
/** * Handles a web socket connection. * * @param socket the opening socket. */ @Override public void handle(final ServerWebSocket socket) { LOGGER.info("New web socket connection {}, {}", socket, socket.uri()); if (! configuration.accept(socket.uri())) { LOGGER.warn("Web Socket connection denied on {} by {}", socket.uri(), configuration.name()); return; } final Socket sock = new Socket(socket); accessor.getDispatcher().addSocket(socket.path(), sock); socket.closeHandler(event -> { LOGGER.info("Web Socket closed {}, {}", socket, socket.uri()); accessor.getDispatcher().removeSocket(socket.path(), sock); }); socket.handler(event -> accessor.getDispatcher().received(socket.path(), event.getBytes(), sock)); }
Example #4
Source File: WSLocalHandler.java From vert.x-microservice with Apache License 2.0 | 6 votes |
private void sendToWSService(final ServerWebSocket serverSocket, final String path, final WSEndpoint endpoint) { final EventBus eventBus = vertx.eventBus(); serverSocket.handler(handler -> { try { log("send WS:+ " + endpoint.getUrl()); eventBus.send(path, Serializer.serialize(new WSDataWrapper(endpoint, handler.getBytes())), new DeliveryOptions().setSendTimeout(GlobalKeyHolder.DEFAULT_SERVICE_TIMEOUT)); } catch (IOException e) { e.printStackTrace(); } } ); serverSocket.resume(); //TODO set close handler!! }
Example #5
Source File: RawWebSocketTransport.java From vertx-web with Apache License 2.0 | 5 votes |
RawWSSockJSSocket(Vertx vertx, Session webSession, User webUser, ServerWebSocket ws) { super(vertx, webSession, webUser); this.ws = ws; ws.closeHandler(v -> { // Make sure the writeHandler gets unregistered synchronized (RawWSSockJSSocket.this) { closed = true; } RawWSSockJSSocket.super.close(); }); }
Example #6
Source File: ApolloWSHandlerImpl.java From vertx-web with Apache License 2.0 | 5 votes |
@Override public void handle(RoutingContext routingContext) { MultiMap headers = routingContext.request().headers(); if (headers.contains(CONNECTION) && headers.contains(UPGRADE, WEBSOCKET, true)) { ContextInternal context = (ContextInternal) routingContext.vertx().getOrCreateContext(); ServerWebSocket serverWebSocket = routingContext.request().upgrade(); ApolloWSConnectionHandler connectionHandler = new ApolloWSConnectionHandler(this, context, serverWebSocket); connectionHandler.handleConnection(); } else { routingContext.next(); } }
Example #7
Source File: ApolloWSConnectionHandler.java From vertx-web with Apache License 2.0 | 5 votes |
void handleConnection() { Handler<ServerWebSocket> ch = apolloWSHandler.getConnectionHandler(); if (ch != null) { ch.handle(serverWebSocket); } serverWebSocket.binaryMessageHandler(this::handleBinaryMessage); serverWebSocket.textMessageHandler(this::handleTextMessage); serverWebSocket.closeHandler(this::close); }
Example #8
Source File: ApolloWSConnectionHandler.java From vertx-web with Apache License 2.0 | 5 votes |
private void close(Void v) { subscriptions.values().forEach(Subscription::cancel); Handler<ServerWebSocket> eh = apolloWSHandler.getEndHandler(); if (eh != null) { eh.handle(serverWebSocket); } }
Example #9
Source File: WebSocketTransport.java From vertx-web with Apache License 2.0 | 5 votes |
WebSocketListener(ServerWebSocket ws, SockJSSession session) { this.ws = ws; this.session = session; ws.textMessageHandler(this::handleMessages); ws.closeHandler(v -> { closed = true; session.shutdown(); }); ws.exceptionHandler(t -> { closed = true; session.shutdown(); session.handleException(t); }); }
Example #10
Source File: WSLocalHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
@Override public void findRouteToWSServiceAndRegister(ServerWebSocket serverSocket) { this.vertx.sharedData().<String, ServiceInfoHolder>getClusterWideMap(REGISTRY, onSuccess(resultMap -> resultMap.get(GlobalKeyHolder.SERVICE_HOLDER, onSuccess(resultHolder -> findServiceEntryAndRegisterWS(serverSocket, resultHolder))) )); }
Example #11
Source File: CertInfo.java From vertx-mqtt-broker with Apache License 2.0 | 5 votes |
public CertInfo(ServerWebSocket webSocket) { try { this.certs = webSocket.peerCertificateChain(); } catch(SSLPeerUnverifiedException e) { logger.error(e.getMessage(), e); } }
Example #12
Source File: VertxRequestUpgradeStrategy.java From vertx-spring-boot with Apache License 2.0 | 5 votes |
@Override public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) { LOGGER.debug("Upgrading request to web socket"); ServerHttpRequest request = exchange.getRequest(); HttpServerRequest vertxRequest = ((AbstractServerHttpRequest) request).getNativeRequest(); ServerWebSocket webSocket = vertxRequest.upgrade(); VertxWebSocketSession session = new VertxWebSocketSession(webSocket, handshakeInfoFactory.get(), bufferConverter); return handler.handle(session); }
Example #13
Source File: VertxDispatcherTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testWebSocketSending() throws InterruptedException, IOException { prepareServer(); final ServerWebSocket socket1 = mock(ServerWebSocket.class); final Socket sock = new Socket(socket1); when(socket1.textHandlerID()).thenReturn("/hello"); MyWebSocketListener listener = new MyWebSocketListener(); server.register(listener); server.addSocket("/hello", sock); // The listener should have been notified. assertThat(listener.opened).isNotNull(); server.received("/hello", "message".getBytes(Charsets.UTF_8), sock); // The listener should have received the message. assertThat(listener.lastMessage).isEqualTo("message"); assertThat(listener.lastClient).isEqualTo(WisdomVertxServer.id(sock)); server.send("/hello", WisdomVertxServer.id(sock), "response"); // Write on missing client. server.send("/hello", "missing", "response"); server.publish("/hello", "yep !"); }
Example #14
Source File: WebSocketTestController.java From festival with Apache License 2.0 | 5 votes |
@OnActive public void active(ServerWebSocket serverWebSocket, WebSocketFrame webSocketFrame) { log.info("active......"); JsonObject jsonObject = new JsonObject(); jsonObject.put("type", 1); jsonObject.put("data", "hello"); serverWebSocket.writeTextMessage(jsonObject.encodePrettily()); }
Example #15
Source File: VertxDispatcherTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testWebSocketWithMultiClients() throws InterruptedException, IOException { // Prepare the configuration prepareServer(); final ServerWebSocket socket1 = mock(ServerWebSocket.class); final Socket sock1 = new Socket(socket1); final ServerWebSocket socket2 = mock(ServerWebSocket.class); final Socket sock2 = new Socket(socket2); MyWebSocketListener listener = new MyWebSocketListener(); server.register(listener); server.addSocket("/hello", sock1); // The listener should have been notified. assertThat(listener.opened).isNotNull(); server.received("/hello", "message".getBytes(Charsets.UTF_8), sock1); // The listener should have received the message. assertThat(listener.lastMessage).isEqualTo("message"); assertThat(listener.lastClient).isEqualTo(Integer.toOctalString(socket1.hashCode())); server.addSocket("/hello", sock2); server.received("/hello", "message2".getBytes(Charsets.UTF_8), sock2); assertThat(listener.lastMessage).isEqualTo("message2"); assertThat(listener.lastClient).isEqualTo(Integer.toOctalString(socket2.hashCode())); server.removeSocket("/hello", sock1); server.removeSocket("/hello", sock2); assertThat(listener.closed).isNotNull(); }
Example #16
Source File: WebSocketRouter.java From festival with Apache License 2.0 | 5 votes |
public void doClose(ServerWebSocket serverWebSocket) { if (close == null) { return; } try { ReflectUtils.invokeMethod(bean, close, serverWebSocket); } catch (InvocationTargetException e) { throw new IllegalStateException(e.getCause()); } }
Example #17
Source File: WebSocketRouter.java From festival with Apache License 2.0 | 5 votes |
public void doActive(ServerWebSocket serverWebSocket, WebSocketFrame frame) { if (active == null) { return; } try { ReflectUtils.invokeMethod(bean, active, serverWebSocket, frame); } catch (InvocationTargetException e) { throw new IllegalStateException(e.getCause()); } }
Example #18
Source File: WebSocketTransport.java From vertx-web with Apache License 2.0 | 5 votes |
WebSocketTransport(Vertx vertx, Router router, LocalMap<String, SockJSSession> sessions, SockJSHandlerOptions options, Handler<SockJSSocket> sockHandler) { super(vertx, sessions, options); String wsRE = COMMON_PATH_ELEMENT_RE + "websocket"; router.getWithRegex(wsRE).handler(rc -> { HttpServerRequest req = rc.request(); String connectionHeader = req.headers().get(io.vertx.core.http.HttpHeaders.CONNECTION); if (connectionHeader == null || !connectionHeader.toLowerCase().contains("upgrade")) { rc.response().setStatusCode(400); rc.response().end("Can \"Upgrade\" only to \"WebSocket\"."); } else { ServerWebSocket ws = rc.request().upgrade(); if (log.isTraceEnabled()) log.trace("WS, handler"); SockJSSession session = new SockJSSession(vertx, sessions, rc, options.getHeartbeatInterval(), sockHandler); session.register(req, new WebSocketListener(ws, session)); } }); router.getWithRegex(wsRE).handler(rc -> { if (log.isTraceEnabled()) log.trace("WS, get: " + rc.request().uri()); rc.response().setStatusCode(400); rc.response().end("Can \"Upgrade\" only to \"WebSocket\"."); }); router.routeWithRegex(wsRE).handler(rc -> { if (log.isTraceEnabled()) log.trace("WS, all: " + rc.request().uri()); rc.response().putHeader(HttpHeaders.ALLOW, "GET").setStatusCode(405).end(); }); }
Example #19
Source File: WSLocalHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
private void findServiceEntryAndRegisterWS(final ServerWebSocket serverSocket, final ServiceInfoHolder resultHolder) { if (resultHolder != null) { final String path = serverSocket.path(); log("find entry : " + path); final Optional<Operation> operationResult = findServiceInfoEntry(resultHolder, path); operationResult.ifPresent(op -> createEndpointDefinitionAndRegister(serverSocket) ); } }
Example #20
Source File: WSClusterHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
@Override public void findRouteToWSServiceAndRegister(ServerWebSocket serverSocket) { final SharedData sharedData = this.vertx.sharedData(); sharedData.<String, ServiceInfoHolder>getClusterWideMap(REGISTRY, onSuccess(resultMap -> resultMap.get(GlobalKeyHolder.SERVICE_HOLDER, onSuccess(resultHolder -> findServiceEntryAndRegisterWS(serverSocket, resultHolder, sharedData))) )); }
Example #21
Source File: WSClusterHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
@Override public void findRouteSocketInRegistryAndRemove(ServerWebSocket serverSocket) { final String binaryHandlerID = serverSocket.binaryHandlerID(); final String textHandlerID = serverSocket.textHandlerID(); this.vertx.sharedData().<String, WSEndpointHolder>getClusterWideMap(WS_REGISTRY, onSuccess(registryMap -> registryMap.get(WS_ENDPOINT_HOLDER, wsEndpointHolder -> { retrieveEndpointHolderAndRemove(serverSocket, binaryHandlerID, textHandlerID, registryMap, wsEndpointHolder); })) ); }
Example #22
Source File: WSClusterHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
private void findServiceEntryAndRegisterWS(final ServerWebSocket serverSocket, final ServiceInfoHolder resultHolder, final SharedData sharedData) { if (resultHolder != null) { final String path = serverSocket.path(); log("find entry : " + path); final Optional<Operation> operationResult = findServiceInfoEntry(resultHolder, path); operationResult.ifPresent(op -> createEndpointDefinitionAndRegister(serverSocket, sharedData) ); } }
Example #23
Source File: WSClusterHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
private void getEndpointHolderAndAdd(ServerWebSocket serverSocket, AsyncMap<String, WSEndpointHolder> registryMap) { registryMap.get(WS_ENDPOINT_HOLDER, wsEndpointHolder -> { if (wsEndpointHolder.succeeded()) { updateWSEndpointHolder(serverSocket, registryMap, wsEndpointHolder); } }); }
Example #24
Source File: WSClusterHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
private void updateWSEndpointHolder(ServerWebSocket serverSocket, AsyncMap<String, WSEndpointHolder> registryMap, AsyncResult<WSEndpointHolder> wsEndpointHolder) { log("add entry: " + Thread.currentThread()); final String binaryHandlerId = serverSocket.binaryHandlerID(); final String textHandlerId = serverSocket.textHandlerID(); final String path = serverSocket.path(); final EventBus eventBus = vertx.eventBus(); final WSEndpoint endpoint = new WSEndpoint(binaryHandlerId, textHandlerId, path); final WSEndpointHolder result = wsEndpointHolder.result(); if (result != null) { addDefinitionToRegistry(serverSocket, eventBus, path, endpoint, registryMap, result); } else { createEntryAndAddDefinition(serverSocket, eventBus, path, endpoint, registryMap); } }
Example #25
Source File: WSClusterHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
private void createEntryAndAddDefinition(ServerWebSocket serverSocket, EventBus eventBus, String path, WSEndpoint endpoint, AsyncMap<String, WSEndpointHolder> registryMap) { final WSEndpointHolder holder = new WSEndpointHolder(); holder.add(endpoint); registryMap.put(WS_ENDPOINT_HOLDER, holder, s -> { if (s.succeeded()) { log("OK ADD: " + serverSocket.binaryHandlerID() + " Thread" + Thread.currentThread()); sendToWSService(serverSocket, eventBus, path, endpoint); } } ); }
Example #26
Source File: WSClusterHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
private void addDefinitionToRegistry(ServerWebSocket serverSocket, EventBus eventBus, String path, WSEndpoint endpoint, AsyncMap<String, WSEndpointHolder> registryMap, WSEndpointHolder wsEndpointHolder) { wsEndpointHolder.add(endpoint); registryMap.replace(WS_ENDPOINT_HOLDER, wsEndpointHolder, s -> { if (s.succeeded()) { log("OK REPLACE: " + serverSocket.binaryHandlerID() + " Thread" + Thread.currentThread()); sendToWSService(serverSocket, eventBus, path, endpoint); } } ); }
Example #27
Source File: MQTTWebSocket.java From vertx-mqtt-broker with Apache License 2.0 | 5 votes |
public MQTTWebSocket(Vertx vertx, ConfigParser config, ServerWebSocket netSocket, Map<String, MQTTSession> sessions) { super(vertx, config, sessions); logger.info(String.format("MQTT new TCP connection: [%s:%s > %s:%s]", netSocket.remoteAddress().host(), netSocket.remoteAddress().port(), netSocket.localAddress().host(), netSocket.localAddress().port() )); this.webSocket = netSocket; }
Example #28
Source File: WSClusterHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
private void retrieveEndpointHolderAndRemove(ServerWebSocket serverSocket, String binaryHandlerID, String textHandlerID, AsyncMap<String, WSEndpointHolder> registryMap, AsyncResult<WSEndpointHolder> wsEndpointHolder) { if (wsEndpointHolder.succeeded()) { final WSEndpointHolder result = wsEndpointHolder.result(); if (result != null) { findEndpointAndRemove(serverSocket, binaryHandlerID, textHandlerID, registryMap,result); } } }
Example #29
Source File: WSClusterHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
private void findEndpointAndRemove(ServerWebSocket serverSocket, String binaryHandlerID, String textHandlerID, AsyncMap<String, WSEndpointHolder> registryMap, WSEndpointHolder wsEndpointHolder) { final List<WSEndpoint> all = wsEndpointHolder.getAll(); final Optional<WSEndpoint> first = all.stream().filter(e -> e.getBinaryHandlerId().equals(binaryHandlerID) && e.getTextHandlerId().equals(textHandlerID)).findFirst(); if (first.isPresent()) { first.ifPresent(endpoint -> { wsEndpointHolder.remove(endpoint); registryMap.replace(WS_ENDPOINT_HOLDER, wsEndpointHolder, replaceHolder -> log("OK REMOVE: " + serverSocket.binaryHandlerID() + " succeed:" + replaceHolder.succeeded())); }); } }
Example #30
Source File: WSRouteMatcher.java From vert.x-microservice with Apache License 2.0 | 5 votes |
public void accept(ServerWebSocket ws){ final String path = ws.path(); if(routes.containsKey(path)) { sessions.put(ws,path); Handler handler = routes.get(path); ws.handler(handler); }else { //TODO error handling } }