I am fairly new to Python and trying to write a fairly simple EventSource server to spit out some data (for now just a test string) ever 5 seconds. It works fine when I connect with my javascript client, but then eventually starts producing SSL errors. These errors don't seem to prevent the script from continuing to work, and ES messages continue to be sent, but ideally I'd like to find a solution.

My code is as follows:

import json
import time
from flask import Flask, Response
from flask_sslify import SSLify

app = Flask(__name__)
sslify = SSLify(app)

@app.route('/events')
def events():
    def generate():
        while True:
            yield "data: hi there\n\n"
            time.sleep(5)

    response = Response(generate(), content_type='text/event-stream')
    response.headers['Access-Control-Allow-Origin'] = 'https://example.com'
    return response

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=4443, ssl_context=('server.crt', 'server.key'))

When I run that code and access via the browser I get the following error (which appears to occur randomly and repeatedly):

D:\WebRoot\Python>py ESServer.py
 * Serving Flask app 'ESServer'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on https://127.0.0.1:4443
 * Running on https://x.x.x.x:4443
Press CTRL+C to quit
 * Debugger PIN: 115-453-164
10.7.102.201 - - [21/Feb/2024 15:32:12] "GET /events HTTP/1.1" 200 -
10.7.102.201 - - [21/Feb/2024 15:34:55] "GET /events HTTP/1.1" 200 -
Error on request:
Traceback (most recent call last):
  File "D:\Python311\Lib\site-packages\werkzeug\serving.py", line 362, in run_wsgi
    execute(self.server.app)
  File "D:\Python311\Lib\site-packages\werkzeug\serving.py", line 326, in execute
    write(data)
  File "D:\Python311\Lib\site-packages\werkzeug\serving.py", line 298, in write
    self.wfile.write(hex(len(data))[2:].encode())
  File "D:\Python311\Lib\socketserver.py", line 834, in write
    self._sock.sendall(b)
  File "D:\Python311\Lib\ssl.py", line 1241, in sendall
    v = self.send(byte_view[count:])
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Python311\Lib\ssl.py", line 1210, in send
    return self._sslobj.write(data)
           ^^^^^^^^^^^^^^^^^^^^^^^^
ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:2423)

I'm not sure if it's a client side issue or a server side issue; nor whether it's an issue with MY code or something in the SSL library itself. FWIW I have the latest version of flask and flask_sslify installed.

0

There are 0 best solutions below