Python實現簡單的HttpServer

見到過一道筆試題,大概就是用任意編程語言實現http server的基本功能,能實現解析與響應,網上參考改了下:

#!/usr/bin/python 
import socket
def HttpResponse(header,whtml):
  f = file(whtml)
  contxtlist = f.readlines()
  context = ''.join(contxtlist)
  response = "%s %d\n\n%s\n\n" % (header,len(context),context)
  return response

HOST = "x.x.x.x."
PORT = x

httpheader = '''''\ 
HTTP/1.1 200 OK 
Context-Type: text/html 
Server: Python-slp version 1.0 
Context-Length: '''

lisfd = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
lisfd.bind((HOST, PORT))
lisfd.listen(2)
confd,addr = lisfd.accept()
confd.send(HttpResponse(httpheader,'/tmp/index.html'))          
confd.close()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章