北漂IT民工 的博客

Python实现的HTTP Server Push的代码

#!/usr/bin/python

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

from datetime import datetime

import time

BOUNDARY = ‘####DATA####’

SEND_BOUNDARY = ‘–’ + BOUNDARY + ‘n’


class MyServer(BaseHTTPRequestHandler):

def do_GET(self):

self.send_response(200, ‘OK’)

self.send_header(‘Content-type’, ‘mulitpart/x-mixed-replace;boundary=’ +

BOUNDARY)

self.wfile.write(SEND_BOUNDARY)

i = 0

self.send_header(‘Content-type’, ‘text/html;charset=utf-8’)

self.end_headers();

self.wfile.write( ““)

self.wfile.write( ““)

self.wfile.write( “Hello world“)

self.wfile.write( ““)

self.wfile.write( ““)

self.wfile.write( “ start ed “)

self.wfile.write( ““)

self.wfile.write( “n”)

while(True):

self.wfile.write( ““)

self.wfile.write( ““)

self.wfile.write( “Hello world“)

self.wfile.write( ““)

self.wfile.write( ““)

self.wfile.write( “hello” + datetime.now().isoformat() + ““)

self.wfile.write( ““)

self.wfile.write( “n”)

self.wfile.flush()

#self.wfile.write(SEND_BOUNDARY)

i += 1

print “loop = %s” % i

time.sleep(3)


@staticmethod

def serve_forever(port):

HTTPServer((‘’, port), MyServer).serve_forever()


if name == “main“:

MyServer.serve_forever(9090)