Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useState, useEffect, useRef } from 'react';
- const ChatClient = () => {
- const [socket, setSocket] = useState(null);
- const [messages, setMessages] = useState([]);
- const [message, setMessage] = useState('');
- const [typingStatus, setTypingStatus] = useState('');
- const typingTimeout = useRef(null);
- useEffect(() => {
- const jwt = localStorage.getItem('token');
- const ws = new WebSocket(`ws://localhost:8003/ws/chat/?token=${jwt}`);
- ws.onopen = () => {
- console.log("WebSocket (client) connection opened");
- setSocket(ws);
- };
- ws.onmessage = (event) => {
- const data = JSON.parse(event.data);
- console.log("Client received data from server:", data);
- switch (data.type) {
- case 'message':
- setMessages((prev) => [...prev, data]);
- if (ws && ws.readyState === WebSocket.OPEN) {
- console.log("Client sending 'message_read' to server...");
- ws.send(JSON.stringify({ type: 'message_read' }));
- }
- break;
- case 'message_read':
- console.log("Client received 'message_read' event from server:", data);
- setMessages((prev) => [
- ...prev,
- { message: "Message read", sender_role: "system" },
- ]);
- break;
- case 'typing':
- console.log("Client received 'typing' event from server:", data);
- setTypingStatus('Admin is typing...');
- if (typingTimeout.current) clearTimeout(typingTimeout.current);
- typingTimeout.current = setTimeout(() => setTypingStatus(''), 3000);
- break;
- default:
- console.warn("Client received unknown message type:", data.type);
- }
- };
- ws.onclose = () => {
- console.log("WebSocket (client) connection closed");
- };
- return () => {
- ws.close();
- };
- }, []);
- const sendMessage = () => {
- if (socket && socket.readyState === WebSocket.OPEN && message.trim() !== '') {
- console.log("Client sending message to server:", message);
- socket.send(JSON.stringify({ type: 'message', message }));
- setMessages((prev) => [
- ...prev,
- { message, sender_role: 'client' },
- ]);
- setMessage('');
- } else {
- console.log("Client: Socket not open or message empty, not sending.");
- }
- };
- const handleTyping = () => {
- if (socket && socket.readyState === WebSocket.OPEN) {
- console.log("Client sending 'typing' notification to server...");
- socket.send(JSON.stringify({ type: 'typing' }));
- }
- };
- return (
- <div>
- <h1>Client Chat</h1>
- <div style={{ height: '200px', overflowY: 'auto', border: '1px solid #ccc', padding: '10px' }}>
- {messages.map((msg, index) => (
- <p key={index}>
- {msg.sender_role === 'system' ? (
- <span style={{ fontStyle: 'italic', color: 'gray' }}>{msg.message}</span>
- ) : (
- <>
- <strong>{msg.sender_role === 'admin' ? 'Admin' : 'You'}:</strong> {msg.message}
- </>
- )}
- </p>
- ))}
- {typingStatus && (
- <p style={{ fontStyle: 'italic', color: 'gray' }}>{typingStatus}</p>
- )}
- </div>
- <input
- type="text"
- value={message}
- onChange={(e) => {
- setMessage(e.target.value);
- handleTyping();
- }}
- placeholder="Type your message"
- />
- <button onClick={sendMessage}>Send</button>
- </div>
- );
- };
- export default ChatClient;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement