一、增加依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二、编写配置类
package com.framework.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* WebMvc配置
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 支持websocket
* 如果不使用内置tomcat,则无需配置
* @return
*/
@Bean
public ServerEndpointExporter createServerEndExporter(){
return new ServerEndpointExporter();
}
}
三、处理类
package com.framework.modules.zz.controller;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* websocket服务端
*/
@Component
@ServerEndpoint(value = "/myWebSocket")
public class MyWebSocket {
//用来存放每个客户端对应的MyWebSocket对象
private static CopyOnWriteArraySet<MyWebSocket> user = new CopyOnWriteArraySet<MyWebSocket>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
@OnMessage
public void onMessage(String message,Session session) throws IOException {
//群发消息
for (MyWebSocket myWebSocket : user) {
myWebSocket.session.getBasicRemote().sendText(session.getId()+"说:"+message);
//myWebSocket.session.getBasicRemote().sendText("<img src=''/>");
}
}
@OnOpen
public void onOpen(Session session){
System.out.println(session.getId()+" open...");
this.session = session;
user.add(this);
}
@OnClose
public void onClose(){
System.out.println(this.session.getId()+" close...");
user.remove(this);
}
@OnError
public void onError(Session session,Throwable error){
System.out.println(this.session.getId()+" error...");
error.printStackTrace();
}
}
四、html页面测试
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>测试</title>
<style>
#message{
height: 520px;
border-bottom: 1px solid gray;
padding: 20px 30px;
}
#container{
margin: 0 auto;
width: 720px;
border: 1px solid gray
}
input{
width: 300px;
height: 36px;
border: 1px solid gray;
background:none;
outline:none;
}
input:focus{
border-color: yellow;
}
button{
height: 36px;
}
</style>
</head>
<body>
<div id="container">
<div id="message">
</div>
<div>
<input id="text" type="text" placeholder="输入内容..."/>
<button onclick="send()">发送消息</button>
</div>
</div>
<script th:inline="javascript" type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:9000/myWebSocket");
}
else {
alert('当前浏览器不支持websocket');
}
//发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
var data = event.data;
document.getElementById('message').innerHTML += data+'<br/>';
}
//连接成功建立的回调方法
websocket.onopen = function () {
console.log("onopen...");
}
//连接关闭的回调方法
websocket.onclose = function () {
console.log("onclose...");
}
//连接发生错误的回调方法
websocket.onerror = function () {
console.log("onerror...");
};
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
</script>
</body>
</html>
最终效果:
参考链接:https://blog.youkuaiyun.com/chen_jia_hao/article/details/82388149