vue3和springboot利用websocket通讯

打印 上一主题 下一主题

主题 1568|帖子 1568|积分 4704

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
前端端口:9090
后端端口:8080
vue3

引入依靠:
   npm install sockjs-client @stomp/stompjs
  vue页面
  1. <template>
  2.   <div>
  3.     <h1>WebSocket 示例</h1>
  4.     <button @click="sendMessage">发送消息</button>
  5.     <div>
  6.       {{ messages }}
  7.     </div>
  8.   </div>
  9. </template>
  10. <script setup lang="ts">
  11. import { onBeforeUnmount, onMounted, ref } from "vue";
  12. import SockJS from "sockjs-client";
  13. import { Stomp } from "@stomp/stompjs";
  14. const messages = ref();
  15. let stompClient: any = null;
  16. //websocket连接
  17. const connect = () => {
  18.   const socket = new SockJS("http://localhost:8080/ws");
  19.   stompClient = Stomp.over(socket);
  20.   stompClient.connect(
  21.     {},
  22.     (frame: string) => {
  23.       console.log("Connected: " + frame);
  24.       stompClient.subscribe("/topic/greetings", (message: { body: string }) => {
  25.         console.log("Received: " + message.body);
  26.         messages.value = message.body;
  27.         //messages.value.push(message.body);
  28.       });
  29.     },
  30.     (error: string) => {
  31.       console.error("Error: " + error);
  32.     }
  33.   );
  34. };
  35. //发送消息
  36. const sendMessage = () => {
  37.   if (stompClient && stompClient.connected) {
  38.     stompClient.send("/app/hello", {}, "hello, world");
  39.   } else {
  40.     console.error("No STOMP connection available");
  41.   }
  42. };
  43. onMounted(() => {
  44.   connect();
  45. });
  46. onBeforeUnmount(() => {
  47.   if (stompClient) {
  48.     stompClient.disconnect();
  49.   }
  50. });
  51. </script>
  52. <style scoped>
  53. /* 添加你的样式 */
  54. </style>
复制代码
springboot

引入依靠
  1.         <!-- Spring Boot WebSocket依赖 -->
  2.         <dependency>
  3.             <groupId>org.springframework.boot</groupId>
  4.             <artifactId>spring-boot-starter-websocket</artifactId>
  5.         </dependency>
复制代码
websocket设置
  1. import org.springframework.context.annotation.Configuration;
  2. import org.springframework.messaging.simp.config.MessageBrokerRegistry;
  3. import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
  4. import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
  5. import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
  6. @Configuration
  7. @EnableWebSocketMessageBroker
  8. public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
  9.     @Override
  10.     public void configureMessageBroker(MessageBrokerRegistry config) {
  11.         config.enableSimpleBroker("/topic"); // 使用内存中的简单代理来广播消息
  12.         config.setApplicationDestinationPrefixes("/app"); // 客户端发送消息到服务器的前缀
  13.     }
  14.     @Override
  15.     public void registerStompEndpoints(StompEndpointRegistry registry) {
  16.         registry.addEndpoint("/ws")
  17.                 .setAllowedOrigins("http://localhost:9090") // 允许的来源列表
  18.                 .withSockJS(); // 注册 WebSocket 端点,并启用 SockJS 备份传输方式
  19.     }
  20. }
复制代码
controller
  1.     @MessageMapping("/hello")
  2.     @SendTo("/topic/greetings")
  3.     public String greeting(String message) {
  4.         System.out.println(message);
  5.         return "你好";
  6.     }
复制代码
测试

点击按钮

 另一个毗连这个广播主题的页面也会接受到信息

后端控制台

 
 ===============================注意====================================
这里阐明一下,假如vue文件里的onMounted将毗连和发送两个函数写在一起,即:
   onMounted(() => {
  connect();
    sendMessage();
});
   你会发现sendMessage()里并没有发送到后端,后端你也没有返回消息。
原因:
异步性:WebSocket 毗连是异步的。这意味着 connect 函数会立即返回,而实际的毗连过程会在之后发生。因此,假如您在 connect 函数返回后立即调用 sendMessage,stompClient 大概还没有被乐成初始化,因为毗连大概还没有创建。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

王海鱼

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表