pom文件中引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置类
@Component
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
controller层代码
@RestController
@RequestMapping("/test")
@Slf4j
public class WebsocketTest {
@Autowired
private Websocket websocket;
@RequestMapping(value = "/a",method = RequestMethod.GET)
public String test(String a){
if (a!=null){
websocket.sendMessage("heheh");
} return a;
}
}
service层代码
@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class Websocket {
private Session session;
private static CopyOnWriteArraySet<Websocket> websocket = new CopyOnWriteArraySet<>();
@OnOpen
public void onOpen(Session session){
this.session =session;
websocket.add(this);
log.info("【websocket消息】有新的连接,总数:{}",websocket.size());
}
@OnClose
public void onClose(){
websocket.remove(this);
log.info("【websocket消息】连接断开,总数:{}",websocket.size());
}
@OnMessage
public void onMessage(String message){
log.info("【websocket消息】,收到客户端发来的消息:{}",message);
}
public void sendMessage(String message){
for (Websocket websocket : websocket) {
log.info("【websocket消息】广播消息:{}",message);
try {
websocket.session.getBasicRemote().sendText(message);
}
catch (Exception e){
e.printStackTrace();
} }
}
}
前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webSocket</title>
</head>
<body>
websocket测试
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
var websocket = null;
if ('WebSocket' in window) {
websocket = new WebSocket('ws:/localhost:8080/webSocket');
} else {
alert('该浏览器不支持websocket!');
}
websocket.onopen = function (event) {
console.log('建立连接');
}
websocket.onclose = function (event) {
console.log('连接关闭');
}
websocket.onmessage = function (event) {
console.log('收到消息:' + event.data)
alert("收到服务端消息");
}
websocket.onerror = function () {
alert('websocket通信发生错误!');
}
window.onbeforeunload = function () {
websocket.close();
}
</script>
</body>
</html>
运行代码
页面
postman测试
页面弹窗显示