问题
Here is a part of my React component:
import React from 'react';
import { Client } from '@stomp/stompjs';
class Balance extends React.Component {
componentDidMount() {
const client = new Client({
brokerURL: 'ws://localhost:8080/stomp',
debug: (str) => {
console.log(str);
},
});
client.onConnect(() => {
console.log('onConnect');
client.subscribe('/topic/balance', message => {
console.log(message);
})
});
client.activate();
}
...
It looks like connection was established according to the debug output to browser's console:
Opening Web Socket...
Web Socket Opened...
>>> CONNECT
accept-version:1.0,1.1,1.2
heart-beat:10000,10000
Received data
<<< CONNECTED
heart-beat:0,0
version:1.2
content-length:0
connected to server undefined
However, I don't see a message 'onConnect' in console, which means client.onConnect
was never fired.
Therefore I can't subscribe to a topic.
What could be a problem here?
UPDATE:
回答1:
According to author it was a mix up in syntax of the library.
The corrected code from my question look as the following:
import React from 'react';
import { Client } from '@stomp/stompjs';
class Balance extends React.Component {
componentDidMount() {
// The compat mode syntax is totally different, converting to v5 syntax
// Client is imported from '@stomp/stompjs'
this.client = new Client();
this.client.configure({
brokerURL: 'ws://localhost:8080/stomp',
onConnect: () => {
console.log('onConnect');
client.subscribe('/topic/balance', message => {
console.log(message);
})
},
// Helps during debugging, remove in production
debug: (str) => {
console.log(new Date(), str);
}
});
this.client.activate();
}
...
I created a full working example in my repo.
来源:https://stackoverflow.com/questions/52941127/unable-to-subscribe-on-topic-using-stomp-stompjs