Search in sources :

Example 1 with WebSocketSession

use of io.micronaut.websocket.WebSocketSession in project micronaut-core by micronaut-projects.

the class BinaryChatServerWebSocket method onOpen.

@OnOpen
public void onOpen(String topic, String username, WebSocketSession session) {
    assert ServerRequestContext.currentRequest().isPresent();
    Set<? extends WebSocketSession> openSessions = session.getOpenSessions();
    System.out.println("Server session opened for username = " + username);
    System.out.println("Server openSessions = " + openSessions);
    for (WebSocketSession openSession : openSessions) {
        if (isValid(topic, session, openSession)) {
            String msg = "[" + username + "] Joined!";
            System.out.println("Server sending msg = " + msg);
            openSession.sendSync(msg.getBytes());
        }
    }
}
Also used : WebSocketSession(io.micronaut.websocket.WebSocketSession) OnOpen(io.micronaut.websocket.annotation.OnOpen)

Example 2 with WebSocketSession

use of io.micronaut.websocket.WebSocketSession in project micronaut-core by micronaut-projects.

the class BinaryChatServerWebSocket method onMessage.

@OnMessage
public void onMessage(String topic, String username, byte[] message, WebSocketSession session) {
    assert ServerRequestContext.currentRequest().isPresent();
    Set<? extends WebSocketSession> openSessions = session.getOpenSessions();
    System.out.println("Server received message = " + new String(message));
    System.out.println("Server openSessions = " + openSessions);
    for (WebSocketSession openSession : openSessions) {
        if (isValid(topic, session, openSession)) {
            String msg = "[" + username + "] " + new String(message);
            System.out.println("Server sending msg = " + msg);
            openSession.sendSync(msg.getBytes());
        }
    }
}
Also used : WebSocketSession(io.micronaut.websocket.WebSocketSession) OnMessage(io.micronaut.websocket.annotation.OnMessage)

Example 3 with WebSocketSession

use of io.micronaut.websocket.WebSocketSession in project micronaut-core by micronaut-projects.

the class NettyServerWebSocketHandler method createWebSocketSession.

@Override
protected NettyWebSocketSession createWebSocketSession(ChannelHandlerContext ctx) {
    String id = originatingRequest.getHeaders().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
    final Channel channel = ctx.channel();
    NettyWebSocketSession session = new NettyWebSocketSession(id, channel, originatingRequest, mediaTypeCodecRegistry, webSocketVersion.toHttpHeaderValue(), ctx.pipeline().get(SslHandler.class) != null) {

        private final ConvertibleValues<Object> uriVars = ConvertibleValues.of(uriVariables);

        @Override
        public Optional<String> getSubprotocol() {
            return Optional.ofNullable(subProtocol);
        }

        @Override
        public Set<? extends WebSocketSession> getOpenSessions() {
            return webSocketSessionRepository.getChannelGroup().stream().flatMap((Function<Channel, Stream<WebSocketSession>>) ch -> {
                NettyWebSocketSession s = ch.attr(NettyWebSocketSession.WEB_SOCKET_SESSION_KEY).get();
                if (s != null && s.isOpen()) {
                    return Stream.of(s);
                }
                return Stream.empty();
            }).collect(Collectors.toSet());
        }

        @Override
        public void close(CloseReason closeReason) {
            super.close(closeReason);
            webSocketSessionRepository.removeChannel(ctx.channel());
        }

        @Override
        public Optional<Principal> getUserPrincipal() {
            return originatingRequest.getAttribute(HttpAttributes.PRINCIPAL, Principal.class);
        }

        @Override
        public ConvertibleValues<Object> getUriVariables() {
            return uriVars;
        }
    };
    webSocketSessionRepository.addChannel(channel);
    return session;
}
Also used : Function(java.util.function.Function) ConvertibleValues(io.micronaut.core.convert.value.ConvertibleValues) CloseReason(io.micronaut.websocket.CloseReason) Channel(io.netty.channel.Channel) Principal(java.security.Principal) NettyWebSocketSession(io.micronaut.http.netty.websocket.NettyWebSocketSession) NettyWebSocketSession(io.micronaut.http.netty.websocket.NettyWebSocketSession) WebSocketSession(io.micronaut.websocket.WebSocketSession)

Example 4 with WebSocketSession

use of io.micronaut.websocket.WebSocketSession in project micronaut-core by micronaut-projects.

the class BinaryChatServerWebSocket method onClose.

@OnClose
public void onClose(String topic, String username, WebSocketSession session) {
    assert ServerRequestContext.currentRequest().isPresent();
    Set<? extends WebSocketSession> openSessions = session.getOpenSessions();
    System.out.println("Server session closing for username = " + username);
    for (WebSocketSession openSession : openSessions) {
        if (isValid(topic, session, openSession)) {
            String msg = "[" + username + "] Disconnected!";
            System.out.println("Server sending msg = " + msg);
            openSession.sendSync(msg.getBytes());
        }
    }
}
Also used : WebSocketSession(io.micronaut.websocket.WebSocketSession) OnClose(io.micronaut.websocket.annotation.OnClose)

Example 5 with WebSocketSession

use of io.micronaut.websocket.WebSocketSession in project micronaut-core by micronaut-projects.

the class NettyServerWebSocketBroadcaster method broadcast.

@Override
public <T> Publisher<T> broadcast(T message, MediaType mediaType, Predicate<WebSocketSession> filter) {
    return Flux.create(emitter -> {
        try {
            WebSocketFrame frame = webSocketMessageEncoder.encodeMessage(message, mediaType);
            webSocketSessionRepository.getChannelGroup().writeAndFlush(frame, ch -> {
                Attribute<NettyWebSocketSession> attr = ch.attr(NettyWebSocketSession.WEB_SOCKET_SESSION_KEY);
                NettyWebSocketSession s = attr.get();
                return s != null && s.isOpen() && filter.test(s);
            }).addListener(future -> {
                if (!future.isSuccess()) {
                    Throwable cause = extractBroadcastFailure(future.cause());
                    if (cause != null) {
                        emitter.error(new WebSocketSessionException("Broadcast Failure: " + cause.getMessage(), cause));
                        return;
                    }
                }
                emitter.next(message);
                emitter.complete();
            });
        } catch (Throwable e) {
            emitter.error(new WebSocketSessionException("Broadcast Failure: " + e.getMessage(), e));
        }
    }, FluxSink.OverflowStrategy.BUFFER);
}
Also used : Attribute(io.netty.util.Attribute) ChannelGroupException(io.netty.channel.group.ChannelGroupException) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) ClosedChannelException(java.nio.channels.ClosedChannelException) Predicate(java.util.function.Predicate) Publisher(org.reactivestreams.Publisher) FluxSink(reactor.core.publisher.FluxSink) Singleton(jakarta.inject.Singleton) Channel(io.netty.channel.Channel) Flux(reactor.core.publisher.Flux) MediaType(io.micronaut.http.MediaType) Nullable(io.micronaut.core.annotation.Nullable) Map(java.util.Map) WebSocketBroadcaster(io.micronaut.websocket.WebSocketBroadcaster) Requires(io.micronaut.context.annotation.Requires) WebSocketSessionException(io.micronaut.websocket.exceptions.WebSocketSessionException) WebSocketSession(io.micronaut.websocket.WebSocketSession) Attribute(io.netty.util.Attribute) WebSocketSessionException(io.micronaut.websocket.exceptions.WebSocketSessionException) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame)

Aggregations

WebSocketSession (io.micronaut.websocket.WebSocketSession)6 MediaType (io.micronaut.http.MediaType)2 Channel (io.netty.channel.Channel)2 InterceptedMethod (io.micronaut.aop.InterceptedMethod)1 Requires (io.micronaut.context.annotation.Requires)1 Nullable (io.micronaut.core.annotation.Nullable)1 ConvertibleValues (io.micronaut.core.convert.value.ConvertibleValues)1 NettyWebSocketSession (io.micronaut.http.netty.websocket.NettyWebSocketSession)1 CloseReason (io.micronaut.websocket.CloseReason)1 WebSocketBroadcaster (io.micronaut.websocket.WebSocketBroadcaster)1 OnClose (io.micronaut.websocket.annotation.OnClose)1 OnMessage (io.micronaut.websocket.annotation.OnMessage)1 OnOpen (io.micronaut.websocket.annotation.OnOpen)1 WebSocketClientException (io.micronaut.websocket.exceptions.WebSocketClientException)1 WebSocketSessionException (io.micronaut.websocket.exceptions.WebSocketSessionException)1 ChannelGroupException (io.netty.channel.group.ChannelGroupException)1 WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)1 Attribute (io.netty.util.Attribute)1 Singleton (jakarta.inject.Singleton)1 Closeable (java.io.Closeable)1