编写代码
maven pom文件引入websocket依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
websocket配置类
如果不使用spring内置的tomcat,则无需配置此类
@Configuration
public class WebSocketConfig {
/**
* 支持websocket
* 如果不使用内置tomcat,则无需配置
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
websocketServer
@Slf4j
@Component
@ServerEndpoint(value = "/myWebSocket")
public class MyWebSocketServer {
//用来存放每个客户端对应的MyWebSocket对象
private static CopyOnWriteArraySet<MyWebSocketServer> user = new CopyOnWriteArraySet<MyWebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
@OnOpen
public void onOpen(Session session){
this.session = session;
user.add(this);
log.info("websocket-用户 {} 连接",this.session.getId());
}
@OnClose
public void onClose(){
user.remove(this);
log.info("websocket-用户 {} 关闭连接",this.session.getId());
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送的消息
* @param session 连接
*/
@OnMessage
public void onMessage(String message,Session session){
log.info("websocket-收到了客户端消息: {}",message);
}
@OnError
public void onError(Session session,Throwable error){
error.printStackTrace();
log.info("websocket-用户 {} 连接错误 : {}",this.session.getId(),error.toString());
}
//发送消息
public void sendMessage(String message) {
//遍历储存的Websocket
for (MyWebSocketServer webSocket : user) {
//发送
try {
webSocket.session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
controller层调用websockerServer
@ApiOperation("添加备注")
@PostMapping("/remark")
@ResponseBody
public CommonResult remarkCounsel(@RequestBody @Validated SolveOrRemarkCounselDto remarkCounselDto){
opLogService.remarkCounsel(remarkCounselDto);
webSocketServer.sendMessage("有新的备注!");
return CommonResult.success(null,"备注提交成功!");
}
js代码
let websocket = null;
if ('WebSocket' in window){
websocket = new WebSocket("ws://"+ window.location.host +"/iqas-dev-zyp/myWebSocket")
}else {
$.alert('当前浏览器不支持websocket')
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
console.log(event.data);
//这里写接受到消息后前端的方法逻辑...
}
//连接成功建立的回调方法
websocket.onopen = function () {
console.log("websocket onopen...");
}
//连接关闭的回调方法
websocket.onclose = function () {
console.log("websocket onclose...");
}
//连接发生错误的回调方法
websocket.onerror = function () {
console.log("websocket connect error...");
$.alert("websocket connect error...");
};
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
实现效果
当用户添加备注时,controller层会调用service将用户备注的信息存入数据库中,同时通知websocketServer有新的备注信息,之后前端请求数据库将备注信息展示在页面,实现当前在该页面的用户可以即时看到其他用户添加的备注。
遇到的问题
外网无法连接到websocket,解决方案参考:
https://www.hi-linux.com/posts/42176.html
参考资料
https://www.jianshu.com/p/6f15e25bbb62
https://blog.csdn.net/weixin_42364319/article/details/104274029