首页 > 解决方案 > ReactJS:STOMP 订阅多个主题

问题描述

我的 React 代码创建了一个到我们公司的 ActiveMQ 5.15.5 服务器的 WebSocket 连接,然后订阅了以下两个主题:salarydecoding. 问题是代码只能订阅其中一个主题。它不能同时订阅两者。

const client = window.Stomp.client(`ws://${ipAddress}:61614`, 'aj6.stomp');
const headers = { id: 'username' };
client.debug = null;
client.connect('user', 'pass', () => {
    client.subscribe(  
      '/topic/salary',  //BREAKPOINT was set here
      message => {
        const body = JSON.parse(message.body);
        if (body && body.pcId) {
          salaries[body.pcId] = body;
          setState({ salaries});
        }
      },
      headers,
    );
    client.subscribe(
      '/topic/decoding',  //BREAKPOINT was set here
      message => {
        const newBody = JSON.parse(message.body);
        if (newBody && newBody.PcID) {
          consoleMessage[newBody.PcID] = newBody;
          setState({ consoleMessage });
        }
      },
      headers,
    );
});

client.subscribe('/topic/decoding...所以在上面的代码中,我在and处设置了一个断点client.subscribe('/topic/salary...。我看到它只订阅/topic/decoding但不订阅/topic/salary

有谁知道我可以如何解决这个问题,以便它订阅这两个主题?

标签: reactjsactivemqspring-websocketstomp

解决方案


尝试创建 2 个客户端,例如:

const salaryClient = window.Stomp.client(`ws://${ipAddress}:61614`, 'aj6.stomp');
const salaryHeaders = { id: 'salary' };
salaryClient.debug = null;
salaryClient.connect('user', 'pass', () => {
    salaryClient.subscribe(  
      '/topic/salary',
      message => {
        const body = JSON.parse(message.body);
        if (body && body.pcId) {
          salaries[body.pcId] = body;
          setState({ salaries});
        }
      },
      salaryHeaders,
    );
});
const decodingClient = window.Stomp.client(`ws://${ipAddress}:61614`, 'aj7.stomp');
const decodingHeaders = { id: 'decoding' };
decodingClient.debug = null;
decodingClient.connect('user', 'pass', () => {
    decodingClient.subscribe(
      '/topic/decoding',
      message => {
        const newBody = JSON.parse(message.body);
        if (newBody && newBody.PcID) {
          consoleMessage[newBody.PcID] = newBody;
          setState({ consoleMessage });
        }
      },
      decodingHeaders,
    );
});

推荐阅读