admin管理员组

文章数量:1123885

I have a web socket server set up, and a python script that sends messages to the websocket server. My react app is supposed to read these messages, but it doesn't get them. When I send messages from the react app, it receives a response from the web socket server, but only then.

Web socket server code:

# echo_server.py
import asyncio
import websockets
import logging

logging.basicConfig(level=logging.DEBUG)

async def echo(websocket):
    async for message in websocket:
        logging.debug(f"Received message: {message}")
        await websocket.send(message)

async def main():
    async with websockets.serve(echo, "0.0.0.0", 6789):
        await asyncio.Future()  # Run forever

if __name__ == "__main__":
    logging.debug("Starting WebSocket server")
    asyncio.run(main())

Python Script to send messages code:

import asyncio
import websockets

async def send_messages():
    uri = "ws://3.140.79.204:6789"  # Replace with your WebSocket server URI
    async with websockets.connect(uri) as websocket:
        messages = ["Hello from Python!", "How are you?", "This is a test message.", "Goodbye!"]
        
        for message in messages:
            await websocket.send(message)
            print(f"Sent message: {message}")
            await asyncio.sleep(1)  # Wait for 1 second between messages

if __name__ == "__main__":
    asyncio.run(send_messages())

React component (took directly from here):

import React, { useState, useCallback, useEffect } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';

const WebsocketTesting = () => {
  //Public API that will echo messages sent to it back to the client
  const [socketUrl, setSocketUrl] = useState('ws://3.140.79.204:6789');
  const [messageHistory, setMessageHistory] = useState([]);

  const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl);

  useEffect(() => {
    if (lastMessage !== null) {
      setMessageHistory((prev) => prev.concat(lastMessage));
    }
  }, [lastMessage]);

  const handleClickChangeSocketUrl = useCallback(
    () => setSocketUrl('wss://demos.kaazing/echo'),
    []
  );

  const handleClickSendMessage = useCallback(() => sendMessage('Hello'), []);

  const connectionStatus = {
    [ReadyState.CONNECTING]: 'Connecting',
    [ReadyState.OPEN]: 'Open',
    [ReadyState.CLOSING]: 'Closing',
    [ReadyState.CLOSED]: 'Closed',
    [ReadyState.UNINSTANTIATED]: 'Uninstantiated',
  }[readyState];

  return (
    <div>
      <button onClick={handleClickChangeSocketUrl}>
        Click Me to change Socket Url
      </button>
      <button
        onClick={handleClickSendMessage}
        disabled={readyState !== ReadyState.OPEN}
      >
        Click Me to send 'Hello'
      </button>
      <span>The WebSocket is currently {connectionStatus}</span>
      {lastMessage ? <span>Last message: {lastMessage.data}</span> : null}
      <ul>
        {messageHistory.map((message, idx) => (
          <span key={idx}>{message ? message.data : null}</span>
        ))}
      </ul>
    </div>
  );
};

export default WebsocketTesting;

As I described, the react app will receive echoed messages it sends to the server
enter image description here

And the python server will receive the echoes from the messages it sends
python3 send_messages_test.py

Sent message: Hello from Python!

Sent message: How are you?

Sent message: This is a test message.

Sent message: Goodbye!

But the react app won't read the messages that the python script sends, why is this?

本文标签: reactjsReact App Not Receiving Web Socket Messages When Python Script Sends themStack Overflow