1

How can I keep my Python HTTP server connected(streaming) to my browser in real time? (Update image to infinity) Like raspberry pi's motion eye

class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.send_header("Connection", "keep-alive")
        self.send_header("keep-alive", "timeout=999999, max=99999")
        self.end_headers()

    
    def do_GET(self):

        #self.send_response(204)
        #self.end_headers()
        
        if self.path == '/':
            self.path = 'abc.jpg'
        return http.server.SimpleHTTPRequestHandler.do_GET(self)

# Create an object of the above class
handler_object = MyHttpRequestHandler

PORT = 8000
my_server = socketserver.TCPServer(("", PORT), handler_object)

# Star the server
my_server.serve_forever()
HK boy
  • 1,398
  • 11
  • 17
  • 25
INTJ
  • 11
  • 1

2 Answers2

0

Just keep writing, as in:

while True:
    self.wfile.write(b"data")

This however won't get you into eventstream / server sent events territory, without using helper external libraries, as far as I'm aware.

ikiddo
  • 1
0

I came across the same issue, I then found by chance (after much debugging) that you need to send linebreaks (\r\n or \n\n) to have the packets sent:

import http.server
import time


class MyHttpRequestHandler(http.server.BaseHTTPRequestHandler):
    value = 0
    # One can also set protocol_version = 'HTTP/1.1' here
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.send_header("Connection", "keep-alive")
        self.end_headers()
        while True:
            self.wfile.write(str(self.value).encode())
            self.wfile.write(b'\r\n')  # Or \n\n, necessary to flush
            self.value += 1
            time.sleep(1)


PORT = 8000

my_server = http.server.HTTPServer(("", PORT), MyHttpRequestHandler)

# Start the server
my_server.serve_forever()

This enables you to send Server-sent Events (SSE) or HTTP long poll, or even json/raw http streams with the http.server library.

As the comment in the code says, you can also set the protocol version to HTTP/1.1 to enable keepalive by default. If you do so, you will have to specify Content-Length for every sent packet, otherwise the connection will never be terminated.

It is probably best to combine this with a threaded server to allow concurrent connections, as well as maybe setting a keepalive on the socket itself.

MayeulC
  • 1,628
  • 17
  • 24