Thursday, 16 February 2023

How to receive data on a websocket, and use it?

Since I'm still fairly new to Javascript (and Node.js and React), I've got another question for the experts here. I'm trying to get some client/server communication set up, and while I think I have data sending set up for this, I'm not sure that I have the receiving part correct. Best as I can figure, this either isn't returning in time for me to pass back to calling code, or I'm not getting the order of operations correct. My code:

import React, { useEffect, useState, WebSocket } from 'react';

const URL_WEB_SOCKET = 'wss://localhost:5000/ws';
const URL_WEB_LOGIN = 'wss://localhost:5000/ws';
let socketMessage = "";

function useWebSockets (message, isControl) {
  let data = "";
  React.useEffect(() => {
    const websocket = new WebSocket(isControl ? URL_WEB_LOGIN : URL_WEB_SOCKET);
    
    websocket.onmessage = function(event) {
      socketMessage = event.data.toString();

      // first attempt
      //data = event.data.toString();//JSON.parse(event.data);
      //return event.data;
    }

    websocket.onopen = () => {
      websocket.send(message);
    }
  }, [])
}

export function getData(message) {
  const ws = new useWebSockets(message, false);
  return ws.data;
}

export function Login(message) {
  let ws = new useWebSockets(message, true);
  return ws.data;
}

This is all in one file. I'm calling the Login and getData functions from another file, and they should be returning whatever data is passed back by the socket. However, I'm getting undefined errors. Do I have this set up correctly? Thanks.

Update I have updated my code to the above, and I now can get back the websocket itself, but still no data (It's always blank). I think my code here is mostly correct, but from what I know about programming, I wonder if Javascript is dealing with this in an asynchronous manner and needing to wait for the onmessage to trigger before I can read the results. The server is sending data back fine, so how can I get the data and push it back through the Login and GetData functions to the calling code?



from How to receive data on a websocket, and use it?

No comments:

Post a Comment