Spring Boot使用WebSocket实现用户之间发送消息
步骤
1.在pom中添加websocket依赖
<!-- websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.向容器添加ServerEndpointExporter组件
@Configuration
public class WebSocketConfig{
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
3.配置服务器端点类
注解**@ServerEndpoint**标记一个服务器端点类,用来响应和处理用户发送的消息。参数为客户端连接WebSocket需要的地址。其中可以用占位符传递参数,用法类似Controller中的路径变量。
@Service
//sessionId指定当前连接的用户将要给其他哪个用户发消息
@ServerEndpoint("/s/{sessionId}")
public class WebSocketServiceImpl{
private static ConcurrentHashMap<String, Session> map = new ConcurrentHashMap<>();
//建立连接
@OnOpen
public void onOpen(Session session){
System.out.println("onOpen()" + session.getId());
map.put(session.getId(),session);
}
//关闭连接
@OnClose
public void onClose(Session session){
System.out.println("onClose()" + session.getId());
map.remove(session.getId());
}
//服务端收到客户端发送的消息
@OnMessage
public void onMessage(@PathParam("sessionId")String sessionId , String message, Session session) throws IOException{
System.out.println("onMessage(),用户发送的信息为:" + message + ",sessionId=" + session.getId());
//发送给sessionId为2的用户
Session target=map.get(String.valueOf(sessionId));
if(target!=null){
//同步发送
target.getBasicRemote().sendText(message+"\n");
//异步发送
//target.getAsyncRemote().sendText(message+"\n");
}
}
//服务端产生错误
@OnError
public void onError(Throwable error){
System.out.println("onError(),message=" + error.getMessage());
}
}
服务器端到此配置完毕,接下来配置客户端。
4.配置客户端
用户发送消息页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>消息</h1>
<p id="text"></p>
<hr>
<input id="sessionId" placeholder="输入要发送用户的SessionId">
<button onclick="initWebSocket()">建立连接</button>
<input id="message" type="text" placeholder="输入要发送的消息">
<button onclick="sendMessage()">发送消息</button>
<button onclick="closeWebsocket()">关闭连接</button>
</body>
<script>
var webSocket;
var text=document.getElementById("text");
function initWebSocket() {
var sessionId=document.getElementById("sessionId").value;
//判断浏览器是否支持WebSocket
if("WebSocket" in window){
//注意这里如果是https的话,协议要改成wss而不是ws
webSocket=new WebSocket("ws://localhost:443/s/"+sessionId);
}
else {
alert("不支持WebSocket!");
}
//连接服务器端点成功后的回调
webSocket.onopen=function () {
showMessage("连接成功")
};
webSocket.onclose=function () {
showMessage("关闭连接");
};
//收到服务器端点发送来的消息后的回调
webSocket.onmessage=function (message) {
showMessage(message.data);
};
webSocket.onerror=function () {
showMessage("连接出错");
};
}
function sendMessage() {
var msg=document.getElementById("message").value;
//向服务器端点发送消息
webSocket.send(msg);
}
function closeWebsocket() {
//关闭与服务器端点的连接
webSocket.close();
}
function showMessage(message) {
text.innerText+=(message);
}
</script>
</html>
注意:
如果网站用的是http,那么连接服务器端点的url为
"ws://localhost:443/s/"
如果网站用的是https,需要将ws改为wss
"wss://localhost:443/s/"