ssebin /

#!/usr/bin/env python

from gevent.pywsgi import WSGIServer
from gevent import monkey, sleep

# monkeypatch all socket things before importing anything else

import os
import urlparse

class App(object):
    def __init__(self, *args, **kwargs):
        # Read homepage and hold in memory.
        here = os.path.dirname(os.path.abspath(__file__))
        with open(os.path.join(here, 'home.html')) as f:
            self.html =

    def __call__(self, environ, start_response):
        path = urlparse.urlparse(environ['PATH_INFO']).path
        if path in ('', '/'):
            return self.homepage(environ, start_response)
        elif path == '/events/':
            return, start_response)

        return self.four_o_four(environ, start_response)

    def homepage(self, environ, start_response):
        start_response("200 OK", [("Content-Type", "text/html")])
        return self.html

    def events(self, environ, start_response):
        start_response("200 OK", [("Content-Type", "text/event-stream")])

        counter = 0
        while True:
            counter += 1
            # The simplest SSE event is a single "data: " line, terminated with
            # two newlines.
            yield "data: %s\n\n" % counter

    def four_o_four(self, environ, start_response):
        start_response("404 NOT FOUND", [("Content-Type", "text/plain")])
        return "404 Not Found"

if __name__ == '__main__':
    address = '', int(os.getenv('PORT', 8000))
    server = WSGIServer(address, App())
        print "Server running on port %s:%d. Ctrl+C to quit" % address
    except KeyboardInterrupt:
        print "Bye bye"