728x90
반응형
ws 프로토콜 기반으로 클라이언트와 서버 사이에 지속적인 양방향 연결 스트림을 만들어 주는 기술
WebSocket 연결
- 브라우저에서 WebSocket 제공 시간이 걸리니 useEffect 내에서 연결
- WebScoket은 꼭 전역변수로 사용
const ws = useRef(null);
useEffect(() => webSocketLogin(), []);
const webSocketLogin = useCallback(() => {
// 웹소켓 연결
ws.current = new WebSocket('ws://localhost:8080/socket/chat');
// 메세지 받으면 행동
ws.current.onmessage = message => setSocketData(JSON.parse(message.data));, []);
Message 전송
// 소켓이 생성됐으나 미연결 상태로 연결되면 메세지 전송
if (ws.current.readyState === 0) {
ws.current.onopen = () => ws.current.send(sendData);
} else {
// 메시지 전송
ws.current.send(sendData);
}
Node WebSocket Server
const {WebSocketServer} = require("ws"); const wss = new WebSocketServer({ port: 8080 }); //연결 wss.on('connection', function connection(ws, request) { wss.clients.forEach(client => { client.send(`새로운 유저가 접속했습니다. 현재 유저 ${
arkhyeon.tistory.com
Spring WebSocket Server - React
WebSocketChat.java WebSocket의 열고, 닫고, 메세지 받을 때 어떻게 동작할 지 작성 WebSocketConfiguration.java Spring Bean은 싱글톤으로 관리하지만 @ServerEndpoint 어노테이션인 클래스는 WebSocket 생성 시 마다 인
arkhyeon.tistory.com
GitHub - arkhyeon/WebSocket
Contribute to arkhyeon/WebSocket development by creating an account on GitHub.
github.com
728x90
반응형
'React' 카테고리의 다른 글
Yarn StoryBook 실행 Error #22431 (0) | 2024.01.29 |
---|---|
useEffect no dependency (0) | 2023.11.14 |
React 빌드 용량 최적화 - Vite rollupOptions manualChunks (0) | 2023.09.07 |
Dynamic Import / Lazy Loading - 코드 스플리팅[Code Splitting] (0) | 2023.09.07 |
Compound Component 패턴 (0) | 2023.07.12 |