Zuma32

webscoket

Aug 7th, 2025
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.72 KB | Source Code | 0 0
  1. import React, { useEffect, useState } from 'react';
  2.  
  3. function WebSocketDemo({token, getNotifications}) {
  4.   const [messages, setMessages] = useState([]);
  5.   const [ws, setWs] = useState(null);
  6.   const [info, setInfo] = useState(null);
  7.  
  8.   useEffect(() => {
  9.     // Create WebSocket connection.
  10.     console.log("in websocket ", token)
  11.     const socket = new WebSocket(`ws://localhost:8000/ws/notifications/?token=${token}`);
  12.  
  13.     // Connection opened
  14.     socket.onopen = () => {
  15.       console.log('WebSocket connected');
  16.       console.log(token)
  17.       // socket.send(JSON.stringify({ message: 'Hello server!' }));
  18.     };
  19.  
  20.     // Listen for messages
  21.     socket.onmessage = (event) => {
  22.       const data = JSON.parse(event.data);
  23.      
  24.       if (data.message.role === "driver"){
  25.         if (typeof getNotifications === "function") {
  26.           // extract notification pk
  27.           getNotifications(data.message.notification_pk);
  28.         }
  29.       }
  30.       else if(data.message.role === "user") {
  31.         if (typeof getNotifications === "function") {
  32.           // extract notification pk
  33.           getNotifications(data.message);
  34.         }
  35.       }
  36.        
  37.     };
  38.  
  39.     // Connection closed
  40.     socket.onclose = (event) => {
  41.       console.log('WebSocket disconnected:', event);
  42.     };
  43.  
  44.     // Handle errors
  45.     socket.onerror = (error) => {
  46.       console.error('WebSocket error:', error);
  47.     };
  48.  
  49.     setWs(socket);
  50.  
  51.     // Cleanup on component unmount
  52.     return () => {
  53.       socket.close();
  54.     };
  55.   }, []);
  56.  
  57.   const send_message = () => {
  58.     ws.send(
  59.       JSON.stringify({
  60.         receiver_id: 37,
  61.         message : info
  62.       })
  63.     )
  64.   }
  65.  
  66.   return (
  67.     null
  68.   );
  69. }
  70.  
  71. export default WebSocketDemo;
  72.  
Advertisement
Add Comment
Please, Sign In to add comment