https://stomp-js.github.io/guide/stompjs/using-stompjs-v5.html
import { Client } from '@stomp/stompjs';
// 연결하기 -> 공식 문서 내용
const client = new StompJs.Client({
brokerURL: 'ws://localhost:15674/ws',
connectHeaders: {
login: 'user',
passcode: 'password',
},
debug: function (str) {
console.log(str);
},
reconnectDelay: 5000,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
});
client.onConnect = function (frame) {
// Do something, all subscribes must be done is this callback
// This is needed because this will be executed after a (re)connect
};
client.onStompError = function (frame) {
// Will be invoked in case of error encountered at Broker
// Bad login/passcode typically will cause an error
// Complaint brokers will set `message` header with a brief message. Body may contain details.
// Compliant brokers will terminate the connection after any error
console.log('Broker reported error: ' + frame.headers['message']);
console.log('Additional details: ' + frame.body);
};
client.activate();
=====================================================================
내가 짠 코드
const clientRef = useRef(
new StompJS.Client({
brokerURL: `${process.env.REACT_APP_API_WEBSOCKET_BASE_URL}`,
})
);
const client = clientRef.current;
client.publish({ // 메세지 보내기 body에 메세지 담기
destination: `/app/api/busker/${userId}/offer`,
body: JSON.stringify({
userId,
offer,
})
})
client.onConnect = (frame) => { // sub는 onconnect 이벤트에 걸어두는 것이 안정적이라고 봄.
console.log("streaming stomp : " + frame);
// sdpOffer를 보내고 Answer를 받음
client.subscribe(`/busker/${userId}/sdpAnswer`, (res) => { //메세지 받기 res로 메세지 받음.
const offerResponse = JSON.parse(res.body);
const answerId = offerResponse.id;
const response = offerResponse.response;
const sdpAnswer = offerResponse.sdpAnswer;
client.subscribe(`/busker/${userId}/iceCandidate`, (res) => {
const iceResponse = JSON.parse(res.body);
if (iceResponse.id === "iceCandidate") {
console.log(koreaTime + " server send ice \n" + iceResponse.candidate.candidate)
const icecandidate = new RTCIceCandidate(iceResponse.candidate)
}
})
}
client.onStompError = (frame) => {
console.log('Broker reported error: ' + frame.headers['message']);
console.log('Additional details: ' + frame.body);
};
// 연결 끊기
client.deactivate().then(r => console.log(r)); // Close the WebSocket connection