Я хочу подписаться на topi c с помощью Sock JS и Stomp Client. Я помещаю подписку на клиента внутри функции onConnect, чтобы убедиться, что Клиент подключен. Это моя конфигурация для:
import getEnvVars from "./environment";
import { socketUrl } from "../services/GlobalUrls";
import SockJS from "sockjs-client";
import { Client } from "@stomp/stompjs";
/**
* Please notice that this import not used on this file
* but used on the library of this file
* so please don't delete it or the app will throw an error
* */
import * as encoding from "text-encoding";
const url = getEnvVars().apiUrl + socketUrl;
let _stompClient = null;
const webSocket = () => {
//const [message, newMessage] = useState();
_stompClient = new Client({
brokerURL: url,
connectHeaders: {},
debug: (str) => {
console.log(str);
},
reconnectDelay: 500,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
logRawCommunication: false,
webSocketFactory: () => {
return SockJS(url);
},
onStompError: (frame) => {
console.log("Stomp Error", frame);
},
onConnect: (frame) => {
console.log("Stomp Connect", frame);
if (_stompClient.connected) {
_stompClient.subscribe("topic/notification", (message) => {
console.log("message");
if (message.body) {
let notification = JSON.parse(message.body);
if (notification.type == "MESSAGE") {
console.log("MESSAGE", notification);
} else if (notification.type == "INVITATION") {
console.log("INVITATION", notification);
} else if (notification.type == "REMOVED") {
console.log("REMOVED", notification);
}
}
});
}
},
onDisconnect: (frame) => {
console.log("Stomp Disconnect", frame);
},
onWebSocketClose: (frame) => {
console.log("Stomp WebSocket Closed", frame);
},
onWebSocketError: (frame) => {
console.log("Stomp WebSocket Error", frame);
},
});
_stompClient.activate();
return _stompClient;
};
export default webSocket;
На моем компоненте своей реакции:
useEffect(() => {
webSocket();
}, []);
Моя отладка показывает следующее:
Opening Web Socket...
accept-version:1.0,1.1,1.2
heart-beat:4000,4000
Web Socket Opened...
heart-beat:0,0
version:1.2
content-length:0
id:sub-0
destination:topic/notification/8
>>> CONNECT
accept-version:1.0,1.1,1.2
heart-beat:4000,4000
Received data
<<< CONNECTED
heart-beat:0,0
version:1.2
content-length:0
connected to server undefined
Stomp Connect FrameImpl {
"_binaryBody": Uint8Array [],
"command": "CONNECTED",
"escapeHeaderValues": false,
"headers": Object {
"heart-beat": "0,0",
"version": "1.2",
},
"isBinaryBody": true,
"skipContentLengthHeader": false,
}
>>> SUBSCRIBE
id:sub-0
destination:topic/notification
Такая же отладка была показана в приложении angular, и я получил сообщение, но на моем ответе родное приложение у меня ничего нет. Angular настройка:
const ws = new SockJS(this.globalService.BASE_URL + "/socket");
this.stompClient = Stomp.over(ws);
this.stompClient.debug = () => {};
const that = this;
this.stompClient.connect({}, function(frame) {
that.stompClient.subscribe(
"/topic/notification",
message => {
if (message.body) {
let notification = JSON.parse(message.body);
if (notification.type == "MESSAGE") {
that.messageListService.setNotificationObs(notification);
} else if (notification.type == "INVITATION") {
that.messageListService.setInvitationNotificationObs(notification);
} else if (notification.type == "REMOVED") {
that.messageListService.removeInvitationNotificationObs(notification);
}
}
}
);
});