Additional shortcut with charset in WebSocketMessage

This commit is contained in:
Rossen Stoyanchev 2018-02-25 14:41:13 -05:00
parent d3eff49c59
commit 9c55dd5961
2 changed files with 17 additions and 5 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -15,6 +15,7 @@
*/
package org.springframework.web.reactive.socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.springframework.core.io.buffer.DataBuffer;
@ -67,13 +68,24 @@ public class WebSocketMessage {
}
/**
* Return the message payload as UTF-8 text. This is a useful for text
* WebSocket messages.
* A variant of {@link #getPayloadAsText(Charset)} that uses {@code UTF-8}
* for decoding the raw content to text.
*/
public String getPayloadAsText() {
return getPayloadAsText(StandardCharsets.UTF_8);
}
/**
* A shortcut for decoding the raw content of the message to text with the
* given character encoding. This is useful for text WebSocket messages, or
* otherwise when the payload is expected to contain text.
* @param charset the character encoding
* @since 5.0.5
*/
public String getPayloadAsText(Charset charset) {
byte[] bytes = new byte[this.payload.readableByteCount()];
this.payload.read(bytes);
return new String(bytes, StandardCharsets.UTF_8);
return new String(bytes, charset);
}
/**

View File

@ -57,7 +57,7 @@ public interface WebSocketSession {
DataBufferFactory bufferFactory();
/**
* Get the flux of incoming messages.
* Get access to the stream of incoming messages.
*/
Flux<WebSocketMessage> receive();