반응형
설명
- 아래에서 만든 WebSocket 서버에 연결하여 통신하는 React WebSocket 예제
모듈 추가
yarn add @stomp/stompjs sockjs-client
프록시 설정
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = (app) => {
app.use(
"/api",
createProxyMiddleware({
target: "http://localhost:8080",
changeOrigin: true,
})
);
app.use(
"/ws-stomp",
createProxyMiddleware({ target: "http://localhost:8080", ws: true })
);
};
App.js
import React, { useEffect, useRef, useState } from "react";
import * as StompJs from "@stomp/stompjs";
import * as SockJS from "sockjs-client";
const ROOM_SEQ = 1;
const App = () => {
const client = useRef({});
const [chatMessages, setChatMessages] = useState([]);
const [message, setMessage] = useState("");
useEffect(() => {
connect();
return () => disconnect();
}, []);
const connect = () => {
client.current = new StompJs.Client({
// brokerURL: "ws://localhost:8080/ws-stomp/websocket", // 웹소켓 서버로 직접 접속
webSocketFactory: () => new SockJS("/ws-stomp"), // proxy를 통한 접속
connectHeaders: {
"auth-token": "spring-chat-auth-token",
},
debug: function (str) {
console.log(str);
},
reconnectDelay: 5000,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
onConnect: () => {
subscribe();
},
onStompError: (frame) => {
console.error(frame);
},
});
client.current.activate();
};
const disconnect = () => {
client.current.deactivate();
};
const subscribe = () => {
client.current.subscribe(`/sub/chat/${ROOM_SEQ}`, ({ body }) => {
setChatMessages((_chatMessages) => [..._chatMessages, JSON.parse(body)]);
});
};
const publish = (message) => {
if (!client.current.connected) {
return;
}
client.current.publish({
destination: "/pub/chat",
body: JSON.stringify({ roomSeq: ROOM_SEQ, message }),
});
setMessage("");
};
return (
<div>
{chatMessages && chatMessages.length > 0 && (
<ul>
{chatMessages.map((_chatMessage, index) => (
<li key={index}>{_chatMessage.message}</li>
))}
</ul>
)}
<div>
<input
type={"text"}
placeholder={"message"}
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyPress={(e) => e.which === 13 && publish(message)}
/>
<button onClick={() => publish(message)}>send</button>
</div>
</div>
);
};
export default App;
실행 결과
- 이미지
참고
반응형
'Development > React' 카테고리의 다른 글
[React] redux-saga (0) | 2020.12.30 |
---|---|
[React] react-redux (0) | 2020.12.30 |
[React] Library (0) | 2020.12.30 |
[React] react-testing-library (0) | 2019.12.29 |
[React] Enzyme (0) | 2019.12.28 |