欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python实现简单http服务器功能

时间:2021-04-04 10:14:37|栏目:Python代码|点击:

背景

写一个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中logging日志库实例详解

栏    目:Python代码

下一篇:python调用函数、类和文件操作简单实例总结

本文标题:python实现简单http服务器功能

本文地址:http://www.codeinn.net/misctech/94238.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有