-
28. Server Sent Event (SSE)Java Script & Type Script 2023. 2. 18. 17:52728x90
SSE-Server Sent Event
서버에서 클라이언트로 데이터를 보내는 단방향 통신
실시간 알림을 구현하며 백엔드분께서 웹소켓 대신 제안하신 SSE!
실시간 채팅과같이 양방향통신이 필요없기 때문에 데이터가 무거워지는 웹소켓보단 SSE를 써보자는 의견이었다.
SSE는 별도의 프로토콜 없이 HTTP 프로토콜만으로 사용 가능하고 훨씬 가볍다.
Event Source
서버와 클라이언트 간 SSE 통신을 하려면 처음에 클라이언트에서 서버로 연결 요청을 보내야 한다.
EventSource는 SSE 연결 요청을 보내기 위해 JavaScript가 제공하는 객체이며, SSE Client API는 EventSource 객체에 포함된다.이벤트 핸들러
- EventSource.onopen : 서버와 연결이 open되었을 때 호출하는 이벤트 핸들러
- EventSource.onmessage : 서버로부터 message를 수신했을 때 호출하는 이벤트 핸들러
- EventSource.onerror : 에러가 발생하거나 EventSource 객체에서 error event가 감지되었을 때 호출하는 이벤트 핸들러
const EventSource = EventSourcePolyfill || NativeEventSource; useEffect(() => { if (loading && isLogin) { let eventSource; const fetchSse = async () => { try { eventSource = new EventSource( `${process.env.REACT_APP_BASE_URL}/api/subscribe`, { headers: { Authorization: getCookie("accessToken"), }, withCredentials: true, } ); /* EVENTSOURCE ONMESSAGE ---------------------------------------------------- */ eventSource.onmessage = async (event) => { const res = await event.data; if (!res.includes("EventStream Created.")) setNewAlarms(true); // 헤더 마이페이지 아이콘 상태 변경 queryClient.invalidateQueries("myprofile"); // 프로필 업데이트 queryClient.invalidateQueries("alertNoti"); // 알람 리스트 개수 변경 queryClient.invalidateQueries("alertLists"); // 알림 목록 업데이트 }; /* EVENTSOURCE ONERROR ------------------------------------------------------ */ eventSource.onerror = async (event) => { if (!event.error.message.includes("No activity")) eventSource.close(); }; } catch (error) {} }; fetchSse(); return () => eventSource.close(); } });
참고한사이트
https://tecoble.techcourse.co.kr/post/2022-10-11-server-sent-events/
728x90'Java Script & Type Script' 카테고리의 다른 글
41.기본이 탄탄해야한다. 탄앤탄스 [useEffect에 대한 고찰] (0) 2023.03.07 33. 항해99 실전프로젝트- 네이버아이디로 로그인 (네이버로그인 API) 소셜로그인 네이버, 네이버로그인 원형 버튼, 버튼 커스텀, 네이버로그인 로그아웃방법, 리액트 코드 (0) 2023.02.27 26. [React] 태그 내 스타일속성 넣기, 별점 구현하기 (0) 2023.01.31 25. [React] 뼈갈넣 회원가입 유효성 검사 (0) 2023.01.28 24. Immer라이브러리와 불변성 관리 (0) 2023.01.11