Vue 通过@stomp/stompjs建立长链接 无法进入connect链接成功的回调 是什么原因?

新手上路,请多包涵

Vue 通过@stomp/stompjs建立长链接 无法进入connect回调

<template>
  <div>
    <h1>WebSocket 长连接示例</h1>
    <button @click="startConnection">开始连接</button>
    <button @click="stopSubscription" :disabled="!isConnected">取消订阅</button>
    <button @click="closeConnection" :disabled="!isConnected">关闭连接</button>
    <input v-model="messageToSend" placeholder="输入消息">
    <button @click="sendMessage" :disabled="!isConnected">发送消息</button>
    <div v-if="receivedMessage">
      <h2>收到的消息:</h2>
      <p>{{ receivedMessage }}</p>
    </div>
  </div>
</template>

<script>
import { Stomp } from '@stomp/stompjs';

export default {
  data() {
    return {
      client: null,
      subscription: null,
      url: 'ws://127.0.0.1:9000',
      topic: '/topic/test',
      customHeaders: {},
      isConnected: false,
      receivedMessage: null,
      messageToSend: '',
    };
  },
  methods: {
    startConnection() {
      console.log('尝试连接到', this.url);
      this.client = Stomp.client(this.url);

      this.client.configure({
        connectHeaders: this.customHeaders,
        heartbeatIncoming: 10,
        heartbeatOutgoing: 20,
        onConnect: (frame) => {
          console.log('连接成功', frame);
          this.isConnected = true;
          this.subscription = this.client.subscribe(this.topic, (message) => {
            console.log('收到消息', message.body);
            this.receivedMessage = message.body;
          });
        },
        onStompError: (error) => {
          console.error('STOMP 错误', error);
          this.handleConnectionError(error);
        },
        onWebSocketClose: (event) => {
          console.error('连接关闭', event);
          this.isConnected = false;
        },
        onWebSocketError: (event) => {
          console.error('WebSocket 错误', event);
          this.handleConnectionError(event);
        },
        debug: (str) => {
          console.log('+++++ DEBUG +++++');
          console.log(new Date(), str);
        }
      });

      this.client.activate();
    },
    stopSubscription() {
      if (this.subscription) {
        this.subscription.unsubscribe();
        console.log('取消订阅');
      }
    },
    closeConnection() {
      if (this.client && this.isConnected) {
        this.client.deactivate(() => {
          console.log('关闭连接');
          this.isConnected = false;
        });
      }
    },
    sendMessage() {
      if (this.client && this.isConnected) {
        const message = { text: this.messageToSend };
        this.client.publish({ destination: this.topic, body: JSON.stringify(message) });
        console.log('消息已发送', message);
      } else {
        console.log('WebSocket 未连接');
      }
    },
    handleConnectionError(error) {
      console.error('WebSocket 连接错误', error);
      this.isConnected = false;
    }
  },
};
</script>

<style scoped>
button {
  margin: 10px;
}

input {
  margin: 10px;
}
</style>
const WebSocket = require('ws');

// 指定自定义端口号
const PORT = 9000;

const server = new WebSocket.Server({ port: PORT });

server.on('connection', (ws) => {
  console.log('客户端已连接');

  ws.on('message', (message) => {
    console.log(`收到消息: ${message}`);
     
    // 发送响应消息
    ws.send(`服务器收到: ${message}`);
  });

  ws.on('close', () => {
    console.log('客户端已断开连接');
  });

  ws.on('error', (error) => {
    console.log(`WebSocket 错误: ${error}`);
  });
});

console.log(`WebSocket 服务器在 ws://localhost:${PORT} 运行`);

如上分别为前后端代码 点击开始链接 启动后端ws服务 后端控制台提示客户端已连接,但是前端onConnect回调一直无法进入 ,只有debug事件回调正常

目前不确定是否真正建立了链接 希望获取onConnect的回调事件

阅读 1.5k
1 个回答

是版本不同的缘故么,看着跟官方示例不太一样
https://github.com/stomp-js/stompjs

<!--
    JSPM Generator Import Map
    Edit URL: https://generator.jspm.io/#U2NgYGBkDM0rySzJSU1hcCguyc8t0AeTWcUO5noGega6SakliaYAYTzJAykA
  -->
<script type="importmap">
  {
    "imports": {
      "@stomp/stompjs": "https://ga.jspm.io/npm:@stomp/stompjs@7.0.0/esm6/index.js"
    }
  }
</script>

<!-- ES Module Shims: Import maps polyfill for modules browsers without import maps support (all except Chrome 89+) -->
<script
  async
  src="https://ga.jspm.io/npm:es-module-shims@1.5.1/dist/es-module-shims.js"
  crossorigin="anonymous"
></script>

<script type="module">
  import { Client } from '@stomp/stompjs';

  const client = new Client({
    brokerURL: 'ws://localhost:15674/ws',
    onConnect: () => {
      client.subscribe('/topic/test01', message =>
        console.log(`Received: ${message.body}`)
      );
      client.publish({ destination: '/topic/test01', body: 'First Message' });
    },
  });

  client.activate();
</script>
import { Client } from '@stomp/stompjs';

import { WebSocket } from 'ws';
Object.assign(global, { WebSocket });

const client = new Client({
  brokerURL: 'ws://localhost:15674/ws',
  onConnect: () => {
    client.subscribe('/topic/test01', message =>
      console.log(`Received: ${message.body}`)
    );
    client.publish({ destination: '/topic/test01', body: 'First Message' });
  },
});

client.activate();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题