org.springframework.web.reactive.socket.WebSocketSession Java Examples

The following examples show how to use org.springframework.web.reactive.socket.WebSocketSession. 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: ReactorNettyWebSocketClient.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Mono<Void> execute(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) {
	return getHttpClient()
			.headers(nettyHeaders -> setNettyHeaders(requestHeaders, nettyHeaders))
			.websocket(StringUtils.collectionToCommaDelimitedString(handler.getSubProtocols()))
			.uri(url.toString())
			.handle((inbound, outbound) -> {
				HttpHeaders responseHeaders = toHttpHeaders(inbound);
				String protocol = responseHeaders.getFirst("Sec-WebSocket-Protocol");
				HandshakeInfo info = new HandshakeInfo(url, responseHeaders, Mono.empty(), protocol);
				NettyDataBufferFactory factory = new NettyDataBufferFactory(outbound.alloc());
				WebSocketSession session = new ReactorNettyWebSocketSession(inbound, outbound, info, factory);
				if (logger.isDebugEnabled()) {
					logger.debug("Started session '" + session.getId() + "' for " + url);
				}
				return handler.handle(session);
			})
			.doOnRequest(n -> {
				if (logger.isDebugEnabled()) {
					logger.debug("Connecting to " + url);
				}
			})
			.next();
}
 
Example #2
Source File: EmployeeWebSocketHandler.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession webSocketSession) {

    Flux<String> employeeCreationEvent = Flux.generate(sink -> {
        EmployeeCreationEvent event = new EmployeeCreationEvent(randomUUID().toString(), now().toString());
        try {
            sink.next(om.writeValueAsString(event));
        } catch (JsonProcessingException e) {
            sink.error(e);
        }
    });

    return webSocketSession.send(employeeCreationEvent
        .map(webSocketSession::textMessage)
        .delayElements(Duration.ofSeconds(1)));
}
 
Example #3
Source File: StreamingLogWebSocketHandler.java    From spring-cloud-app-broker with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession session) {
	String serviceInstanceId = getServiceInstanceId(session);
	LOG.info("Connection established [{}}], service instance {}",
		session.getHandshakeInfo().getRemoteAddress(),
		serviceInstanceId);

	EmitterProcessor<Envelope> processor = processors
		.computeIfAbsent(serviceInstanceId, s -> EmitterProcessor.create());

	eventPublisher.publishEvent(new StartServiceInstanceLoggingEvent(this, serviceInstanceId));
	LOG.info("Published event to start streaming logs for service instance with ID {}", serviceInstanceId);

	return session
		.send(processor.map(envelope -> session
			.binaryMessage(dataBufferFactory -> dataBufferFactory.wrap(Envelope.ADAPTER.encode(envelope)))))
		.then()
		.doFinally(signalType -> afterConnectionClosed(session))
		.doOnError(throwable -> LOG
			.error("Error handling logging stream for service instance " + serviceInstanceId, throwable));
}
 
Example #4
Source File: ServerWebSocketHandler.java    From sample-webflux-websocket-netty with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession session) 
{
	WebSocketSessionHandler sessionHandler = new WebSocketSessionHandler();
	
	sessionHandler
		.connected()
		.subscribe(value -> sessionList.add(sessionHandler));
	
	sessionHandler
		.disconnected()
		.subscribe(value -> sessionList.remove(sessionHandler));
	
	connectedProcessor.sink().next(sessionHandler);
	
	return sessionHandler.handle(session);
}
 
Example #5
Source File: WebsocketRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession session) {
	// pass headers along so custom headers can be sent through
	return client.execute(url, this.headers, new WebSocketHandler() {
		@Override
		public Mono<Void> handle(WebSocketSession proxySession) {
			// Use retain() for Reactor Netty
			Mono<Void> proxySessionSend = proxySession
					.send(session.receive().doOnNext(WebSocketMessage::retain));
			// .log("proxySessionSend", Level.FINE);
			Mono<Void> serverSessionSend = session.send(
					proxySession.receive().doOnNext(WebSocketMessage::retain));
			// .log("sessionSend", Level.FINE);
			return Mono.zip(proxySessionSend, serverSessionSend).then();
		}

		/**
		 * Copy subProtocols so they are available downstream.
		 * @return
		 */
		@Override
		public List<String> getSubProtocols() {
			return ProxyWebSocketHandler.this.subProtocols;
		}
	});
}
 
Example #6
Source File: WebSocketPlugin.java    From soul with Apache License 2.0 6 votes vote down vote up
@NonNull
@Override
public Mono<Void> handle(@NonNull final WebSocketSession session) {
    // pass headers along so custom headers can be sent through
    return client.execute(url, this.headers, new WebSocketHandler() {
    
        @NonNull
        @Override
        public Mono<Void> handle(@NonNull final WebSocketSession webSocketSession) {
            // Use retain() for Reactor Netty
            Mono<Void> sessionSend = webSocketSession
                    .send(session.receive().doOnNext(WebSocketMessage::retain));
            Mono<Void> serverSessionSend = session.send(
                    webSocketSession.receive().doOnNext(WebSocketMessage::retain));
            return Mono.zip(sessionSend, serverSessionSend).then();
        }
    
        @NonNull
        @Override
        public List<String> getSubProtocols() {
            return SoulWebSocketHandler.this.subProtocols;
        }
    });
}
 
Example #7
Source File: ReactorNettyWebSocketClient.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Mono<Void> execute(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) {
	String protocols = StringUtils.collectionToCommaDelimitedString(handler.getSubProtocols());
	return getHttpClient()
			.headers(nettyHeaders -> setNettyHeaders(requestHeaders, nettyHeaders))
			.websocket(protocols, getMaxFramePayloadLength())
			.uri(url.toString())
			.handle((inbound, outbound) -> {
				HttpHeaders responseHeaders = toHttpHeaders(inbound);
				String protocol = responseHeaders.getFirst("Sec-WebSocket-Protocol");
				HandshakeInfo info = new HandshakeInfo(url, responseHeaders, Mono.empty(), protocol);
				NettyDataBufferFactory factory = new NettyDataBufferFactory(outbound.alloc());
				WebSocketSession session = new ReactorNettyWebSocketSession(
						inbound, outbound, info, factory, getMaxFramePayloadLength());
				if (logger.isDebugEnabled()) {
					logger.debug("Started session '" + session.getId() + "' for " + url);
				}
				return handler.handle(session).checkpoint(url + " [ReactorNettyWebSocketClient]");
			})
			.doOnRequest(n -> {
				if (logger.isDebugEnabled()) {
					logger.debug("Connecting to " + url);
				}
			})
			.next();
}
 
Example #8
Source File: MessageWebSocketHandler.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession session) {
	 return session.send(session.receive().map(str -> str.getPayloadAsText())
			 .map(str -> "Howdy, " + str + "? Welcome to the Portal!" )
			 .map(session::textMessage))
			 .delayElement(Duration.ofMillis(2)).log();           
}
 
Example #9
Source File: InboundChatService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
protected Mono<Void> handleInternal(WebSocketSession session) {
	return session
		.receive()
		.log(getUser(session.getId())
			+ "-inbound-incoming-chat-message")
		.map(WebSocketMessage::getPayloadAsText)
		.log(getUser(session.getId())
			+ "-inbound-convert-to-text")
		.flatMap(message ->
			broadcast(message, getUser(session.getId())))
		.log(getUser(session.getId())
			+ "-inbound-broadcast-to-broker")
		.then();
}
 
Example #10
Source File: ReactiveWebSocketHandler.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession webSocketSession) {
    return webSocketSession.send(intervalFlux
      .map(webSocketSession::textMessage))
      .and(webSocketSession.receive()
        .map(WebSocketMessage::getPayloadAsText).log());
}
 
Example #11
Source File: WebSocketIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession session) {
	HttpHeaders headers = session.getHandshakeInfo().getHeaders();
	if (!headers.containsKey("my-header")) {
		return Mono.error(new IllegalStateException("Missing my-header"));
	}
	String payload = "my-header:" + headers.getFirst("my-header");
	WebSocketMessage message = session.textMessage(payload);
	return doSend(session, Mono.just(message));
}
 
Example #12
Source File: WebSocketIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession session) {
	String protocol = session.getHandshakeInfo().getSubProtocol();
	if (!StringUtils.hasText(protocol)) {
		return Mono.error(new IllegalStateException("Missing protocol"));
	}
	List<String> protocols = session.getHandshakeInfo().getHeaders()
			.get(SEC_WEBSOCKET_PROTOCOL);
	assertThat(protocols).contains("echo-v1,echo-v2");
	WebSocketMessage message = session.textMessage(protocol);
	return doSend(session, Mono.just(message));
}
 
Example #13
Source File: WebSocketIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void subProtocol() throws Exception {
	String protocol = "echo-v1";
	String protocol2 = "echo-v2";
	AtomicReference<HandshakeInfo> infoRef = new AtomicReference<>();
	MonoProcessor<Object> output = MonoProcessor.create();

	client.execute(getUrl("/sub-protocol"), new WebSocketHandler() {
		@Override
		public List<String> getSubProtocols() {
			return Arrays.asList(protocol, protocol2);
		}

		@Override
		public Mono<Void> handle(WebSocketSession session) {
			infoRef.set(session.getHandshakeInfo());
			return session.receive().map(WebSocketMessage::getPayloadAsText)
					.subscribeWith(output).then();
		}
	}).block(Duration.ofMillis(5000));

	HandshakeInfo info = infoRef.get();
	assertThat(info.getHeaders().getFirst("Upgrade"))
			.isEqualToIgnoringCase("websocket");

	assertThat(info.getHeaders().getFirst("Sec-WebSocket-Protocol"))
			.isEqualTo(protocol);
	assertThat(info.getSubProtocol()).as("Wrong protocol accepted")
			.isEqualTo(protocol);
	assertThat(output.block(Duration.ofSeconds(5)))
			.as("Wrong protocol detected on the server side").isEqualTo(protocol);
}
 
Example #14
Source File: WebSocketIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private static Mono<Void> doSend(WebSocketSession session,
		Publisher<WebSocketMessage> output) {
	return session.send(output);
	// workaround for suspected RxNetty WebSocket client issue
	// https://github.com/ReactiveX/RxNetty/issues/560
	// return session.send(Mono.delay(Duration.ofMillis(100)).thenMany(output));
}
 
Example #15
Source File: EchoHandler.java    From springboot-learning-example with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> handle(final WebSocketSession session) {
    return session.send(
            session.receive()
                    .map(msg -> session.textMessage(
                            "服务端返回:小明, " + msg.getPayloadAsText())));
}
 
Example #16
Source File: OutboundChatService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
private boolean applicable(Message<String> message, WebSocketSession user) {
	if (message.getPayload().startsWith("@")) {
		String targetUser = message.getPayload()
			.substring(1, message.getPayload().indexOf(" "));

		String sender = message.getHeaders()
			.get(ChatServiceStreams.USER_HEADER, String.class);

		String userName = user.getHandshakeInfo().getPrincipal().block().getName();
		
		return userName.equals(sender) || userName.equals(targetUser);
	} else {
		return true;
	}
}
 
Example #17
Source File: CommentService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public Mono<Void> doHandle(WebSocketSession session) {
	return session.send(this.flux
		.map(comment -> {
			try {
				return mapper.writeValueAsString(comment);
			} catch (JsonProcessingException e) {
				throw new RuntimeException(e);
			}
		})
		.log("encode-as-json")
		.map(session::textMessage)
		.log("wrap-as-websocket-message"))
		.log("publish-to-websocket");
}
 
Example #18
Source File: InboundChatService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
Mono<?> broadcast(String message, WebSocketSession user) {
	return user.getHandshakeInfo().getPrincipal()
		.map(principal -> chatServiceStreams.clientToBroker().send(
			MessageBuilder
				.withPayload(message)
				.setHeader(ChatServiceStreams.USER_HEADER,
					principal.getName())
				.build()));
}
 
Example #19
Source File: OutboundChatService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
protected Mono<Void> doHandle(WebSocketSession session) {
	return session.send(this.flux
		.filter(s -> applicable(s, session))
		.map(this::transform)
		.map(session::textMessage)
		.log(session.getId() +
			"-outbound-wrap-as-websocket-message"))
		.log(session.getId() +
			"-outbound-publish-to-websocket");
}
 
Example #20
Source File: OutboundChatService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
protected Mono<Void> handleInternal(WebSocketSession session) {
	return session
		.send(this.flux
			.filter(s -> validate(s, getUser(session.getId())))
			.map(this::transform)
			.map(session::textMessage)
			.log(getUser(session.getId()) +
				"-outbound-wrap-as-websocket-message"))
		.log(getUser(session.getId()) +
			"-outbound-publish-to-websocket");
}
 
Example #21
Source File: UserParsingHandshakeHandler.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public final Mono<Void> handle(WebSocketSession session) {

	this.userMap.put(session.getId(),
			Stream.of(session.getHandshakeInfo().getUri()
						.getQuery().split("&"))
				.map(s -> s.split("="))
				.filter(strings -> strings[0].equals("user"))
				.findFirst()
				.map(strings -> strings[1])
				.orElse(""));

	return handleInternal(session);
}
 
Example #22
Source File: CommentService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession session) {
	return session.send(this.flux
		.map(comment -> {
			try {
				return mapper.writeValueAsString(comment);
			} catch (JsonProcessingException e) {
				throw new RuntimeException(e);
			}
		})
		.log("encode-as-json")
		.map(session::textMessage)
		.log("wrap-as-websocket-message"))
		.log("publish-to-websocket");
}
 
Example #23
Source File: CommentService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession session) {
	return session.send(this.flux
		.map(comment -> {
			try {
				return mapper.writeValueAsString(comment);
			} catch (JsonProcessingException e) {
				throw new RuntimeException(e);
			}
		})
		.log("encode-as-json")
		.map(session::textMessage)
		.log("wrap-as-websocket-message"))
	.log("publish-to-websocket");
}
 
Example #24
Source File: InboundChatService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession session) {
	return session
		.receive()
		.log("inbound-incoming-chat-message")
		.map(WebSocketMessage::getPayloadAsText)
		.log("inbound-convert-to-text")
		.map(s -> session.getId() + ": " + s)
		.log("inbound-mark-with-session-id")
		.flatMap(this::broadcast)
		.log("inbound-broadcast-to-broker")
		.then();
}
 
Example #25
Source File: OutboundChatService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession session) {
	return session
		.send(this.flux
			.map(session::textMessage)
			.log("outbound-wrap-as-websocket-message"))
		.log("outbound-publish-to-websocket");

}
 
Example #26
Source File: CommentService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession session) {
	return session.send(this.flux
		.map(comment -> {
			try {
				return mapper.writeValueAsString(comment);
			} catch (JsonProcessingException e) {
				throw new RuntimeException(e);
			}
		})
		.log("encode-as-json")
		.map(session::textMessage)
		.log("wrap-as-websocket-message"))
		.log("publish-to-websocket");
}
 
Example #27
Source File: InboundChatService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
protected Mono<Void> doHandle(WebSocketSession session) {
	//end::code[]
	return session.receive()
		.log(session.getId()
			+ "-inbound-incoming-chat-message")
		.map(WebSocketMessage::getPayloadAsText)
		.log(session.getId()
			+ "-inbound-convert-to-text")
		.flatMap(message -> broadcast(message, session))
		.log(session.getId()
			+ "-inbound-broadcast-to-broker")
		.then();
}
 
Example #28
Source File: OutboundChatService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
private boolean applicable(Message<String> message, WebSocketSession user) {
	if (message.getPayload().startsWith("@")) {
		String targetUser = message.getPayload()
			.substring(1, message.getPayload().indexOf(" "));

		String sender = message.getHeaders()
			.get(ChatServiceStreams.USER_HEADER, String.class);

		String userName = user.getHandshakeInfo().getPrincipal().block().getName();
		
		return userName.equals(sender) || userName.equals(targetUser);
	} else {
		return true;
	}
}
 
Example #29
Source File: OutboundChatService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
protected Mono<Void> doHandle(WebSocketSession session) {
	return session.send(this.flux
		.filter(s -> applicable(s, session))
		.map(this::transform)
		.map(session::textMessage)
		.log(session.getId() +
			"-outbound-wrap-as-websocket-message"))
		.log(session.getId() +
			"-outbound-publish-to-websocket");
}
 
Example #30
Source File: CommentService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public Mono<Void> doHandle(WebSocketSession session) {
	return session.send(this.flux
		.map(comment -> {
			try {
				return mapper.writeValueAsString(comment);
			} catch (JsonProcessingException e) {
				throw new RuntimeException(e);
			}
		})
		.log("encode-as-json")
		.map(session::textMessage)
		.log("wrap-as-websocket-message"))
		.log("publish-to-websocket");
}