一、maven引入spring-boot-starter-websocket
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二、配置 ServerEndpointExporter
/**
* @author hyf
* @date 2020/9/15
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
三、websocket服务
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author hyf
* @date 2020/9/15
*/
@ServerEndpoint("/service/websocket")
@Component
public class WebSocket {
Logger logger = LoggerFactory.getLogger(this.getClass());
private static Map<String, WebSocket> clients = new ConcurrentHashMap<>();
private Session session;
@OnOpen
public void onOpen(Session session) throws IOException {
this.session = session;
logger.info("websocket 已连接");
String uuid = UUID.randomUUID().toString();
clients.put(uuid, this);
}
@OnClose
public void onClose() throws IOException {
logger.info("websocket 已断开");
}
@OnMessage
public void onMessage(String message) throws IOException {
logger.info("websocket 推送消息:" + message);
int n = 0;
Iterator<Map.Entry<String, WebSocket>> it = clients.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, WebSocket> item = it.next();
WebSocket ws = item.getValue();
boolean open = ws.session.isOpen();
if (!open) {
clients.remove(item.getKey());
continue;
}
ws.session.getAsyncRemote().sendText(message);
n++;
}
logger.info("websocket 推送消息完成数量:" + n);
}
@OnError
public void onError(Session session, Throwable error) {
logger.error("websocket 异常:" + error);
}
}
四、配置服务可跨域访问(我这里是filter中加了允许跨域访问,根据自身系统配置修改),权限配置中开放“/service/websocket”地址的访问
五、前端实现websocket连接和消息接收
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.1.1/sockjs.min.js"></script>
</head>
<body>
</body>
<script>
var websocaket = null;
if ('WebSocket' in window) {
websocaket = new WebSocket("ws://192.168.68.100:8080/prod-api/service/websocket");
} else {
alert("not support");
}
//连接错误
websocaket.onerror = function () {
alert("连接错误");
}
//连接成功
websocaket.onopen = function () {
alert("连接成功");
}
//收到消息
websocaket.onmessage = function (msg) {
var num = msg.data;
switch (num) {
case "1":
$("id").attr("src", "http://localhost:5581");
break;
case "2":
$("id").attr("src", "https://www.baidu.com");
break;
default:
$("id").attr("src", "https://www.qq.com")
break;
}
}
//连接关闭
websocaket.onclose = function () {
alert("连接关闭");
}
</script>
</html>