[Python] Unexpected message sent to websocket server

Discussão em 'Python' iniciado por Stack, Outubro 5, 2024.

  1. Stack

    Stack Membro Participativo

    My python program includes the below websocket class and function. The fetch_price_data() function is triggered every 60 seconds by client-side JavaScript (index.js).

    class WebSocketClient:
    def __init__(self, url="ws://localhost:8081"):
    self.url = url
    self.ws = None

    def connect(self):
    """Establish connection to the WebSocket server and close immediately."""
    try:
    self.ws = websocket.WebSocket()
    self.ws.connect(self.url)
    print(f"Connected to WebSocket server at {self.url}")
    self.ws.close() # Close the connection right after establishing it
    except Exception as e:
    print(f"Error connecting to WebSocket server: {e}")
    self.ws = None

    def send_data_to_websocket(self, df):
    """Send data to the WebSocket server."""
    try:
    self.ws = websocket.WebSocket()
    self.ws.connect(self.url)
    print("Sending data to WebSocket...")
    json_data = df.to_json(orient="records")

    # Create a structured message with type and payload
    message = {
    'type': 'price_data',
    'payload': json.loads(json_data) # Convert JSON string to a Python object
    }

    # Send the structured message as a JSON string
    self.ws.send(json.dumps(message)) # Serialize the message back to JSON
    print("Data sent:", message)
    self.ws.close()
    except Exception as e:
    print(f"Failed to send data: {e}")

    @app.route('/fetch-price-data', methods=['GET'])
    def fetch_price_data():
    print('Fetching price data.............................')
    df = get_price_data()
    ws_client = WebSocketClient()
    ws_client.send_data_to_websocket(df)
    return jsonify({"status": "Data sent to WebSocket server"}), 200



    The issue I have is that the return statement in the fetch_price_data() (required by Flask) is causing a message to be sent to the websocket server, which I didn't expect. I know this because the server.js file is giving the below output:

    Received a message without a type. Message will not be broadcasted.Parsed message: { status: 'Data sent to WebSocket server' }


    Relevant code in the server.js file:.

    const express = require('express');
    const WebSocket = require('ws');
    const path = require('path');

    const app = express();
    const port = 8080; // For serving the HTML page

    // Serve static HTML file
    app.use(express.static(path.join(__dirname, 'public')));

    // WebSocket server on port 8081
    const wss = new WebSocket.Server({ port: 8081 });

    // Broadcast to all WebSocket clients
    wss.broadcast = function broadcast(data) {
    wss.clients.forEach(function each(client) {
    if (client.readyState === WebSocket.OPEN) {
    client.send(data);
    }
    });
    };

    // Listen for incoming WebSocket messages from Python
    wss.on('connection', function connection(ws) {
    console.log('WebSocket connection established');

    ws.on('message', function incoming(data) {
    const jsonData = data.toString(); // Convert the buffer to string
    console.log('Received data from Python:', jsonData);

    try {
    const message = JSON.parse(jsonData); // Parse incoming message

    // Log parsed message structure
    console.log('Parsed message:', message)

    // Check the message type before broadcasting
    if (message.type) {
    // Broadcast the structured message to all connected clients
    wss.broadcast(jsonData); // Send as is if it's already structured
    } else {
    console.warn('Received a message without a type. Message will not be broadcasted.');
    console.log('Message with warning: ', message)
    }
    } catch (error) {
    console.error('Error parsing incoming message:', error);
    }
    });


    Hoping someone might be able to explain why the return statement in the fetch_price_data() function is sending a message to the websocket server and how to prevent this. I thought it would just be sent back to the HTTP client.

    I'm wondering if this is a valid use of Flask combined with the websocket client.

    Continue reading...

Compartilhe esta Página