目录
1. maven配置
# maven/pom.xml 中添加如下dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. websocket配置
创建wss作为websocket专用package, 新增配置类 WebSocketConfig.java
package com.example.springboottest.wss;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
3. websocket集成
在wss package下创建WebSocketHanddle类,用于websocket的连接管理&收发数据管理, 本代码中,将每次收到的消息,广播到所有在线的websocket上面,另外只传输了userId, 未对userId及session做绑定及验证逻辑,做聊天室或者其他功能,需要对其进行适度扩展。
package com.example.springboottest.wss;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Component
@ServerEndpoint("/ws/channel/{userId}")
public class WebSocketHanddle {
private static Map<String, Session> maps = new HashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId){
String id = session.getId();
log.info("onOpen sessionId:{}, this:{}, userId:{}", id, this.hashCode(), userId);
maps.put(id, session);
}
@OnClose
public void onClose(Session session){
maps.remove(session.getId());
log.info("onClose sessionId:{}, this:{}", session.getId(), this.hashCode());
}
@OnError
public void onError(Session session, Throwable throwable){
log.info("onError sessionId:{}, this:{}, {}", session.getId(), this.hashCode(), throwable.getMessage(), throwable);
}
@OnMessage
public void onMessage(Session session, String text) throws IOException {
log.info("onMessage sessionId:{}, this:{}, message:{}", session.getId(), this.hashCode(), text);
session.getBasicRemote().sendText("服务端已经收到消息:"+ text);
// 广播发送消息给所有在线用户
broadCastMessage(session.getId(), text);
}
/**
* 广播发送消息给在线用户
* @param sendId
* @param text
* @throws IOException
*/
public void broadCastMessage(String sendId, String text) throws IOException {
for(String k : maps.keySet()){
if(sendId.equals(k) == false){
maps.get(k).getBasicRemote().sendText("推送消息:" + text);
}
}
}
}
4. web-html调用
创建 test.html,浏览器页面进行测试
<!DOCTYPE HTML>
<html>
<head>
<title>web socket test</title>
</head>
<body>
<input id="text" type="text" />
<button onclick="send()">发送</button>
<button onclick="close()">关闭</button>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/ws/channel/user_haha");
} else {
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function() {
show("error websocket");
};
//连接成功建立的回调方法
websocket.onopen = function(event) {
show("open websocket");
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
show(event.data);
}
//连接关闭的回调方法
websocket.onclose = function() {
show("close websocket");
}
//监听窗口关闭事件
window.onbeforeunload = function() {
websocket.close();
}
//将消息显示在网页上
function show(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
function close() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
5. 测试