实现方式
在spring中使用websocket有多种方式:
- 在spring mvc中使用,这种不做介绍
- 在webflux中使用,这是咱们本次要介绍的内容
- 直接使用spring + netty做websocket,可以见spring+netty
实现步骤
- 引入相应webflux包
- 实现自定义的请求处理类
WebSocketHandler
- 配置url映射关系及
WebSocketHandlerAdapter
- 通过页面进行测试
MyWebSocketHandler
: 对请求进行处理。这个地方有以下注意事项
- 在真实环境中,需要进行校验,因此需要带参数,在此使用简单的方式,即直接在请求path上带参数
- 消息通过
getPayloadAsText()
获取内容后,再次获取则为空
import com.liukun.test.service.TokenService;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.UrlEncoded;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.reactive.socket.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class MyWebSocketHandler implements WebSocketHandler {
@Autowired
private TokenService tokenService;
@Override
public Mono<Void> handle(WebSocketSession session) {
// 在生产环境中,需对url中的参数进行检验,如token,不符合要求的连接的直接关闭
HandshakeInfo handshakeInfo = session.getHandshakeInfo();
if (handshakeInfo.getUri().getQuery() == null) {
return session.close(CloseStatus.REQUIRED_EXTENSION);
} else {
// 对参数进行解析,在些使用的是jetty-util包
MultiMap<String> values = new MultiMap<String>();
UrlEncoded.decodeTo(handshakeInfo.getUri().getQuery(), values, "UTF-8");
String token = values.getString("token");
boolean isValidate = tokenService.validate(token);
if (!isValidate) {
return session.close();
}
}
Flux<WebSocketMessage> output = session.receive()
.concatMap(mapper -> {
String msg = mapper.getPayloadAsText();
System.out.println("mapper: " + msg);
return Flux.just(msg);
}).map(value -> {
System.out.println("value: " + value);
return session.textMessage("Echo " + value);
});
return session.send(output);
}
}
TokenService
: 校验参数,在生产环境需要对每个连接进行校验,符合要求的才允许连接。
import org.springframework.stereotype.Service;
@Service
public class TokenService {
// demo演示,在引只对长度做校验
public boolean validate(String token) {
if (token.length() > 5) {
return true;
}
return false;
}
}
WebConfig
: 配置类,通过Java Config进行配置。
@Configuration
public class WebConfig {
@Bean
public MyWebSocketHandler getMyWebsocketHandler() {
return new MyWebSocketHandler();
}
@Bean
public HandlerMapping handlerMapping() {
// 对相应的URL进行添加处理器
Map<String, WebSocketHandler> map = new HashMap<>();
map.put("/hello", getMyWebsocketHandler());
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setUrlMap(map);
mapping.setOrder(-1);
return mapping;
}
@Bean
public WebSocketHandlerAdapter handlerAdapter() {
return new WebSocketHandlerAdapter();
}
}
index.html
: 测试代码,内容如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<textarea id="msgBoxs"></textarea><br>
待发送消息:<input type="text" id="msg"><input type="button" id="sendBtn" onclick="send()" value="发送">
<script type="application/javascript">
var msgBoxs = document.getElementById("msgBoxs")
var msgBox = document.getElementById("msg")
document.cookie="token2=John Doe";
var ws = new WebSocket("ws://localhost:9000/hello?token=aabb123&demo=1&userType=0")
ws.onopen = function (evt) {
console.log("Connection open ...");
ws.send("Hello WebSocket!");
}
ws.onmessage = function (evt) {
console.log("Received Message: ", evt.data)
var msgs = msgBoxs.value
msgBoxs.innerText = msgs + "\n" + evt.data
msgBoxs.scrollTop = msgBoxs.scrollHeight;
}
ws.onclose = function (evt) {
console.log("Connect closed.");
}
function send() {
var msg = msgBox.value
ws.send(msg)
msgBox.value = ""
}
</script>
</body>
</html>
直接运行,并输入消息,点击发送,即可见消息经服务端返回
cors
可以有以下方法使其支持cors:
1.直接使自定义的WebSocketHandler
实现CorsConfigurationSource
接口,并返回一个CorsConfiguration
, 如:
public class MyWebSocketHandler implements WebSocketHandler, CorsConfigurationSource {
@Override
public Mono<Void> handle(WebSocketSession session) {
...
}
@Override
public CorsConfiguration getCorsConfiguration(ServerWebExchange exchange) {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("*");
return configuration;
}
}
2.可以在SimpleUrlHandler
上设置corsConfigurations
属性。