springBoot整合websocket

编写代码

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AnswerCoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值