// 引入stomp.js库
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
// WebSocket服务器地址
const ws = new SockJS('http://localhost:8080/my-endpoint');
// 初始化STOMP客户端
const stompClient = Stomp.over(ws);
// 连接STOMP服务器
stompClient.connect({}, frame => {
console.log('Connected: ' + frame);
// 订阅一个路径
stompClient.subscribe('/topic/greetings', message => {
console.log(JSON.parse(message.body).content);
});
}, error => {
console.error('STOMP error:', error);
});
// 发送消息到服务器
stompClient.send("/app/hello", {}, JSON.stringify({ 'name': 'John Doe' }));
// 断开连接
stompClient.disconnect();
3、解决方式:因为当前版本的socketjs内部没有捕捉连接失败抛出的异常,所以最好的解决方式就是对websocket服务器进行健康检查,如果请求服务器有响应说明没挂进行连接,否则就舍弃websocket相关应用,舍车保帅,保证nodejs服务的正常运行。
@GetMapping("/health")
public Health health() {
return 'ok';
}