Python实现简单http服务器

yipeiwu_com6年前服务器

写一个python脚本,实现简单的http服务器功能:

1.浏览器中输入网站地址:172.20.52.163:20014

2.server接到浏览器的请求后,读取本地的index.html文件的内容,回发给浏览器

代码实现

server.py

#!/usr/bin/python 
import socket 
import signal 
import errno 
from time import sleep  
 
 
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 
 
def sigIntHander(signo,frame): 
  print 'get signo# ',signo 
  global runflag 
  runflag = False 
  global lisfd 
  lisfd.shutdown(socket.SHUT_RD) 
 
strHost = "172.20.52.163" 
HOST = strHost #socket.inet_pton(socket.AF_INET,strHost) 
PORT = 20014 
 
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) 
 
signal.signal(signal.SIGINT,sigIntHander) 
 
runflag = True 
while runflag: 
  try: 
    confd,addr = lisfd.accept() 
  except socket.error as e: 
    if e.errno == errno.EINTR: 
      print 'get a except EINTR' 
    else: 
      raise 
    continue 
 
  if runflag == False: 
    break; 
 
  print "connect by ",addr 
  data = confd.recv(1024) 
  if not data: 
    break 
  print data 
  confd.send(HttpResponse(httpheader,'index.html')) 
  confd.close() 
else: 
  print 'runflag#',runflag 
 
print 'Done' 

index.html

<html> 
 <head> 
   <title>Python Server</title> 
 </head> 
 <body> 
  <h1>Hello python</h1> 
  <p>Welcom to the python world</br> 
 </body> 
</html> 

测试

测试结果:

root@cloud2:~/slp/pythonLearning/socket# ./server_v1.py 
connect by ('172.20.52.110', 6096)
GET / HTTP/1.1
Host: 172.20.52.163:20014
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8,en;q=0.6

浏览器

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在Mac OS上使用mod_wsgi连接Python与Apache服务器

一、安装mod_wsgi 3.4: ./configure --with-apxs=/Users/levin/dev/apache2.2.27/bin/apxs --with-pyt...

100行PHP代码实现socks5代理服务器

前两天在B站上看到一个小伙纸100元组装个电脑打LOL画质流畅,突发奇想100行代码能(简单)实现个啥好玩的。我主要是做php开发的,于是就有了本文。 当然,由于php(不算swoole...

Ruby使用eventmachine为HTTP服务器添加文件下载功能

思路: 使用ruby eventmachine和em-http-server gem,完成一个简单的提供文件下载功能的HttpServer; 使用了EM的FileStreamer来异步发...

在windows服务器开启php的gd库phpinfo中未发现

在windows服务器开启php的gd库时,使用cgi之后phpinfo()得到的结果中 Configure Command 中并没有出现gd. Configure Command 后显...

使用Python开发SQLite代理服务器的方法

SQLite数据库使用单个磁盘文件,并且不需要像Oracle、MSSQL、MySQL等数据库管理系统那样启动服务,使用非常灵活方便。但是SQLite也有个很严重的问题,就是没有相应的服务...