Reputation: 23
I am making a Python app to fetch data from my website (which is written in PHP) as a stream.
main.py
import requests
from sseclient import SSEClient
def get_sse(url):
try:
# Make the request to the SSE endpoint
response = requests.get(url, stream=True)
# Create an SSEClient instance with the response stream
client = SSEClient(response)
# Process each event received
for event in client.events():
print(f"Received event: {event.data}")
except requests.exceptions.RequestException as e:
print(f"Request exception: {e}")
except KeyboardInterrupt:
print("Connection closed by user")
if __name__ == "__main__":
sse_url = 'http://mywebsite.com/endpoint.php' # Replace with your SSE endpoint
get_sse(sse_url)
endpoint.php
<?php
// chat.php
// Path to the file that stores the latest message
$messageFile = 'latest_message.txt';
// Function to handle message sending
function handleSendMessage() {
global $messageFile;
// Read the incoming message from POST data
$message = isset($_POST['message']) ? trim($_POST['message']) : '';
// Validate message content (basic validation)
if ($message !== '') {
// Store the message in a file
file_put_contents($messageFile, $message);
echo "Message sent!";
} else {
echo "No message provided!";
}
}
// Function to handle message receiving via SSE
function handleReceiveMessage() {
global $messageFile;
// Set headers for SSE
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// Function to get the latest message from the file
function getLatestMessage() {
global $messageFile;
if (file_exists($messageFile)) {
return file_get_contents($messageFile);
}
return '';
}
// Initial message
$lastMessage = getLatestMessage();
// Loop to send updates to the client
while (true) {
// Get the latest message
$currentMessage = getLatestMessage();
// If there's a new message, send it
if ($currentMessage !== $lastMessage) {
echo "data: $currentMessage\n\n";
ob_flush();
flush();
$lastMessage = $currentMessage;
}
// Sleep for a while to prevent CPU overload
usleep(100000); // 0.1 seconds
}
}
// Determine the type of request and handle accordingly
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
handleSendMessage();
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
handleReceiveMessage();
} else {
echo "Invalid request method!";
}
?>
As you may notice, the PHP works for the sender and the receiver, but I don't think that should cause this following issue:
"Request exception: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))"
There is no CORS, or other kind of security that I know of, but if you strongly believe there is, please tell me. It works fine when doing it in my website itself:
index.html
<!DOCTYPE html>
<html>
<head>
<title>SSE Test</title>
<style>
/* CSS not needed */
</style>
</head>
<body>
<h1>SSE Test</h1>
<div id="messages"></div>
<script>
// Replace with your SSE endpoint
const sseUrl = '/endpoint.php';
// Create a new EventSource instance
const eventSource = new EventSource(sseUrl);
// Function to handle incoming messages
eventSource.onmessage = function(event) {
const messageContainer = document.getElementById('messages');
const messageElement = document.createElement('div');
messageElement.className = 'message';
messageElement.textContent = `Received message: ${event.data}`;
messageContainer.appendChild(messageElement);
messageContainer.scrollTop = messageContainer.scrollHeight; // Auto-scroll to the bottom
};
// Function to handle errors
eventSource.onerror = function(event) {
const messageContainer = document.getElementById('messages');
const messageElement = document.createElement('div');
messageElement.className = 'message';
messageElement.textContent = `Error: ${event.type}`;
messageContainer.appendChild(messageElement);
messageContainer.scrollTop = messageContainer.scrollHeight; // Auto-scroll to the bottom
};
</script>
</body>
</html>
Is there something I am doing wrong? Why does it work on my website but not on my Python file?
Upvotes: 0
Views: 117