(chatting.jsx : 채팅 주요 로직)
const sock = new SockJS("http://3.38.228.74:8080/ws/chat");
const ws = webstomp.over(sock);
const dispatch = useDispatch();
const listReducer = useSelector((state) => state.chatting.chatList);
console.log(listReducer);
// let postId = Number(id) : 임의값이라 일단 주석처리
useEffect(() => {
dispatch(__getinitialChatList({
postId:10,
roomId:1
}));
// 임의의 유저와 룸넘버
return () => {
onbeforeunloda()
};
}, []);
useEffect(() => {
wsConnectSubscribe()
// return () => {
// console.log("???????")
// onbeforeunloda()
// };
}, [listReducer.id]);
const [chatBody, setChatBody] = useState("");
const content = {
sender: "보내는이",
message:chatBody
// 임의의 센더와 useState값의 챗바디
};
let headers = {
Access_Token: localStorage.getItem('Access_Token')
};
// 토큰값이 있어야 채팅이 가능하게 함
function wsConnectSubscribe() {
try {
ws.connect(
headers,(frame) => {
ws.subscribe(
`/sub/1`,
// 데스티네이션
(response) => {
console.log("어떻게 나오는지",response)
let data = JSON.parse(response.body)
dispatch(chatList(data))
// 값이 어떻게 넘어오는지 보는 로직
}
);
},
);
} catch (error) {
}
}
function waitForConnection(ws, callback) {
setTimeout(
function () {
// 연결되었을 때 콜백함수 실행
if (ws.ws.readyState === 1) {
callback();
// 연결이 안 되었으면 재호출
} else {
waitForConnection(ws, callback);
}
},
1 // 밀리초 간격으로 실행
);
}
//stomp 메시지 에러 waitForConnection함수로 해결
const onbeforeunloda = () =>{
try {
ws.disconnect(
()=>{
ws.unsubscribe("sub-0");
clearTimeout(
waitForConnection
)
},
{Access_Token: localStorage.getItem('Access_Token')}
)
}catch (e){
console.log("연결구독해체 에러",e)
}
}
const inputHandler = (e) =>{
setChatBody(e.target.value)
}
// 연결 해제 시 로직
//onSubmitHandler
const onSubmitHandler = (event) =>{
//event.preventDefault()
// if (chatBody=== "" || chatBody === " ") {
// return alert("내용을 입력해주세요.");
// }
waitForConnection(ws,function() {
ws.send(
`/pub/1`,
JSON.stringify(content),
{
Access_Token: localStorage.getItem("Access_Token")
},
)})
setChatBody("")
}
const appKeyPress = (e) => {
if (e.key === 'Enter') {
onSubmitHandler()
setChatBody("")
}
}
//enter시 메시지 보냄
const scrollRef= useRef();
useEffect(() => {
if (scrollRef) {
scrollRef.current.scrollIntoView({
behavior: "smooth",
block: "end",
inline: "nearest",
});
}
}, [listReducer]);
그 외에도 필요한 로직이 있는데 이는 깃허브에 추후 업로드 예정