Advertisement
raffaelegriecoit

chat client

Dec 17th, 2024
12
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.23 KB | None | 0 0
  1. import { useState, useEffect, useRef } from 'react';
  2.  
  3. const ChatClient = () => {
  4. const [socket, setSocket] = useState(null);
  5. const [messages, setMessages] = useState([]);
  6. const [message, setMessage] = useState('');
  7. const [typingStatus, setTypingStatus] = useState('');
  8. const typingTimeout = useRef(null);
  9.  
  10. useEffect(() => {
  11. const jwt = localStorage.getItem('token');
  12. const ws = new WebSocket(`ws://localhost:8003/ws/chat/?token=${jwt}`);
  13.  
  14. ws.onopen = () => {
  15. console.log("WebSocket (client) connection opened");
  16. setSocket(ws);
  17. };
  18.  
  19. ws.onmessage = (event) => {
  20. const data = JSON.parse(event.data);
  21. console.log("Client received data from server:", data);
  22.  
  23. switch (data.type) {
  24. case 'message':
  25. setMessages((prev) => [...prev, data]);
  26. if (ws && ws.readyState === WebSocket.OPEN) {
  27. console.log("Client sending 'message_read' to server...");
  28. ws.send(JSON.stringify({ type: 'message_read' }));
  29. }
  30. break;
  31.  
  32. case 'message_read':
  33. console.log("Client received 'message_read' event from server:", data);
  34. setMessages((prev) => [
  35. ...prev,
  36. { message: "Message read", sender_role: "system" },
  37. ]);
  38. break;
  39.  
  40. case 'typing':
  41. console.log("Client received 'typing' event from server:", data);
  42. setTypingStatus('Admin is typing...');
  43. if (typingTimeout.current) clearTimeout(typingTimeout.current);
  44. typingTimeout.current = setTimeout(() => setTypingStatus(''), 3000);
  45. break;
  46.  
  47. default:
  48. console.warn("Client received unknown message type:", data.type);
  49. }
  50. };
  51.  
  52. ws.onclose = () => {
  53. console.log("WebSocket (client) connection closed");
  54. };
  55.  
  56. return () => {
  57. ws.close();
  58. };
  59. }, []);
  60.  
  61. const sendMessage = () => {
  62. if (socket && socket.readyState === WebSocket.OPEN && message.trim() !== '') {
  63. console.log("Client sending message to server:", message);
  64. socket.send(JSON.stringify({ type: 'message', message }));
  65. setMessages((prev) => [
  66. ...prev,
  67. { message, sender_role: 'client' },
  68. ]);
  69. setMessage('');
  70. } else {
  71. console.log("Client: Socket not open or message empty, not sending.");
  72. }
  73. };
  74.  
  75. const handleTyping = () => {
  76. if (socket && socket.readyState === WebSocket.OPEN) {
  77. console.log("Client sending 'typing' notification to server...");
  78. socket.send(JSON.stringify({ type: 'typing' }));
  79. }
  80. };
  81.  
  82. return (
  83. <div>
  84. <h1>Client Chat</h1>
  85. <div style={{ height: '200px', overflowY: 'auto', border: '1px solid #ccc', padding: '10px' }}>
  86. {messages.map((msg, index) => (
  87. <p key={index}>
  88. {msg.sender_role === 'system' ? (
  89. <span style={{ fontStyle: 'italic', color: 'gray' }}>{msg.message}</span>
  90. ) : (
  91. <>
  92. <strong>{msg.sender_role === 'admin' ? 'Admin' : 'You'}:</strong> {msg.message}
  93. </>
  94. )}
  95. </p>
  96. ))}
  97. {typingStatus && (
  98. <p style={{ fontStyle: 'italic', color: 'gray' }}>{typingStatus}</p>
  99. )}
  100. </div>
  101. <input
  102. type="text"
  103. value={message}
  104. onChange={(e) => {
  105. setMessage(e.target.value);
  106. handleTyping();
  107. }}
  108. placeholder="Type your message"
  109. />
  110. <button onClick={sendMessage}>Send</button>
  111. </div>
  112. );
  113. };
  114.  
  115. export default ChatClient;
  116.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement