http chunked 理解
https://imququ.com/post/transfer-encoding-header-in-http.html
#! /usr/bin/python #coding:utf8 import socket import signal import errno from time import sleep def sig_handler(signo, frame): print "get signo ", signo global runFlg runFlg = False global listeningFd listeningFd.shutdown(socket.SHUT_RD) def http_response_with_content_length(sock): """ 有长度没有 close """ sock.send('HTTP/1.1 200 OK\r\n') sock.send('Content-Length: 12\r\n') sock.send('\r\n') sock.send('Hello World!') def http_response_with_close(sock): """" 没有长度有 close """ sock.send('HTTP/1.1 200 OK\r\n') sock.send('\r\n') sock.send('Hello World!') sock.close() def http_response_chunked(sock): """" 没有长度,没有 close """ sock.send('HTTP/1.1 200 OK\r\n') sock.send('Transfer-Encoding: chunked\r\n') sock.send('\r\n') # 第一个 chunk sock.send('a\r\n') sock.send('1234567890\r\n') # 第二个 chunk sock.send('5\r\n') sock.send('12345\r\n') # 第三个 chunk,也是最后一个 sock.send('0\r\n') sock.send('\r\n') def http_response(sock): """" 没有长度,没有 close """ sock.send('HTTP/1.1 200 OK\r\n') sock.send('\r\n') sock.send('Hello World!') signal.signal(signal.SIGINT, sig_handler) HOST = "127.0.0.1" PORT = 37001 listeningFd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listeningFd.bind((HOST, PORT)) listeningFd.listen(2) print "HttpServer Started" runFlg = True while runFlg: try: connectedFd, addr = listeningFd.accept() except socket.error as e: if e.errno == errno.EINT: print "get a except EINTR" else: raise continue if runFlg == False: break print "connected by ", addr data = connectedFd.recv(1024) if not data: break print data #http_response_with_close(connectedFd) # 流量器能正确处理 #http_response(connectedFd) # 浏览器不能正确处理 pending #http_response_with_content_length(connectedFd) # 浏览器能正确处理 http_response_chunked(connectedFd) # 浏览器能正确处理 else: print "runFlg ", runFlg print "Done"