Spring Boot项目简单使用Websocket

本文介绍了如何在SpringBoot项目中使用WebSocket实现前后端实时通信。前端通过WebSocket建立连接,后端通过@ServerEndpoint注解处理连接、接收和发送消息。Java后端还展示了如何发送广播和单点消息,并提供了相应的Controller接口。此外,文章提到了Postman测试和消息接收的前端处理。
摘要由CSDN通过智能技术生成

Spring Boot项目简单使用Websocket

前端代码

  mounted() {
    // WebSocket 用于建立连接通讯
    if ('WebSocket' in window) {
    // ****可以说成是 建立连接通讯时的用户名  每次发消息时根据这个名字发送到指定的用户
      this.websocket = new WebSocket('ws://localhost:7777/websocket/' 
      + ******)
      this.initWebSocket()
    } else {
      alert('当前浏览器不支持!')
    }
  },
methods: {
initWebSocket () {
      // 连接错误
      this.websocket.onerror = this.setErrorMessage
      // 连接成功
      this.websocket.onopen = this.setOnopenMessage
      // 收到消息的回调
      this.websocket.onmessage = this.setOnmessageMessage
      // 连接关闭的回调
      this.websocket.onclose = this.setOncloseMessage
      // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
      window.onbeforeunload = this.onbeforeunload
    },
    setErrorMessage () {
      console.log('WebSocket连接发生错误 状态码:' + this.websocket.readyState)
    },
    setOnopenMessage () {
      console.log(this.userInfo.userName+'WebSocket连接成功    状态码:' + this.websocket.readyState)
    },
    setOncloseMessage () {
      console.log(this.userInfo.userName+'WebSocket连接关闭    状态码:' + this.websocket.readyState)
    },
    onbeforeunload () {
      this.closeWebSocket()
    },
    closeWebSocket () {
      this.websocket.close()
    },
    //收到消息时
    setOnmessageMessage (event) {
      const datas = JSON.parse(event.data);
      // 根据服务器推送的消息做自己的业务处理
      //console.log('服务端返回:' + datas)
      this.$notify.success({
        title: '提示',
        message: datas.msg,
        duration: 0,
        offset: 100,
      });
    },
    }
    //前端代码差不多是这样了

后端Java代码

pom文件 我只用到了这一个
<!--websocket-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
@Configuration
@EnableWebSocket
public class WebSocketConfig {
    /**
     * 注入ServerEndpointExporter,
     * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
@Component
//value 前端用于连接的  userName前端连接的*****
@ServerEndpoint(value = "/websocket/{userName}")
//此注解相当于设置访问URL
public class WebSocket {

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value="userName")String userName) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(userName, session);
        System.out.println(userName+"【websocket消息】有新的连接,总数为:"+webSockets.size());
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
    }

    // 此为广播消息 广播消息是对全部建立连接通信的用户进行发送消息?
    public void sendAllMessage(String message) {
        for(WebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息:"+message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息 单点消息是一对一发消息?
    public void sendOneMessage(MessageDTO messageDTO) {
        System.out.println("【websocket消息】单点消息:"+messageDTO);
        Session session = sessionPool.get(messageDTO.getReceiveId());
        if (session != null) {
            try {
                //session.getAsyncRemote().sendText(Func.toStr(messageDTO));
                session.getAsyncRemote().sendObject(messageDTO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
@RestController
@AllArgsConstructor
@RequestMapping("/pxx-websocket/")
public class WebSocketController {

    private WebSocket webSocket;
    private RedisUtil redisUtil;
    
    /**
     * 发送广播信息
     * @return
     */
    @GetMapping("/sendAllWebSocket")
    public R test() {
        String text="你们好!这是websocket群体发送!";
        webSocket.sendAllMessage(text);
        return R.data(text);
    }

    /**
     * 发送信息
     * 发送时存入redis 有可能发信息时接收信息的用户未登录
     * @param messageDTO
     * @return
     */
    @PostMapping("/sendOneWebSocket")
    public R sendOneWebSocket(@RequestBody MessageDTO messageDTO) {
        webSocket.sendOneMessage(messageDTO);
        redisUtil.set(CacheNames.ORDER_KEY+messageDTO.getReceiveId(),messageDTO.getMsg());
        return R.data(messageDTO);
    }
}
## MessageDTO 作为一个接受或发送信息的类
//相互记录 接受或发送人在websocket的连接名 可以做一个简单的聊天  我这里用了id进行连接

@Data
public class MessageDTO{

    @ApiModelProperty(value = "收信人")
    private String receiveId;

    @ApiModelProperty(value = "发送人")
    private String sendId;

    @ApiModelProperty(value = "发送人头像")
    private String sendImg;

    @ApiModelProperty(value = "类型")
    private String type;

    @ApiModelProperty(value = "信息")
    private String msg;
}

前端连接F12
连接成功了
这边也可以看到
连接成功
后端控制台
在这里插入图片描述

这样就建立好了通信

可以尝试Postman测试
在这里插入图片描述
收到消息时(setOnmessageMessage )

在这里插入图片描述
在这里插入图片描述
一个简单的推送就做好了

也可以根据自己的情况做一个一对一的聊天,我这边是通过调用接口实现的聊天

具体效果
在这里插入图片描述
一个简单的就做好了

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值