picshop/src/app/admin/chat/page.jsx
2024-12-10 11:55:52 +09:00

73 lines
1.9 KiB
JavaScript

'use client';
import { Button } from '@mui/material';
import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';
let socket;
export default function Chat() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
useEffect(() => {
// Socket.io 클라이언트 초기화
socket = io({ path: '/api/socketio' });
// 서버와 연결 확인
socket.on('connect', () => {
console.log('Connected to server');
});
// 서버에서 메시지를 받는 이벤트 처리
socket.on('message', (data) => {
setMessages((prevMessages) => [...prevMessages, data]);
});
// 컴포넌트 언마운트 시 소켓 연결 종료
return () => {
if (socket) {
socket.disconnect();
}
};
}, []);
const sendMessage = () => {
if (!socket) {
console.error('Socket not initialized');
return;
}
if (input.trim()) {
const message = { user: '셀러테스트', text: input };
// 메시지 서버로 전송
socket.emit('message', message);
setMessages((prevMessages) => [...prevMessages, message]);
setInput('');
}
};
return (
<div>
<div style={{ width:'320px', height: '400px', overflowY: 'scroll', border: '1px solid #ccc', padding: '10px', margin:'auto', borderRadius:'12px'}}>
{messages.map((msg, index) => (
<div key={index}>
<strong>{msg.user}:</strong> {msg.text}
</div>
))}
</div>
<div style={{display:'flex', alignItems:'center', justifyContent:'center', marginTop:'10px'}}>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="입력"
style={{height:'32px', borderRadius:'8px', width:'250px'}}
/>
<Button onClick={sendMessage}>Send</Button>
</div>
</div>
);
}