Код: Выделить всё
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
Код: Выделить всё
Received a message without a type. Message will not be broadcasted.Parsed message: { status: 'Data sent to WebSocket server' }
Код: Выделить всё
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);
}
});
Мне интересно, допустимо ли это использование Flask в сочетании с клиентом веб-сокета.
Подробнее здесь: https://stackoverflow.com/questions/790 ... ket-server