Python实现简单http服务器


本文摘自php中文网,作者不言,侵删。

这篇文章主要为大家详细介绍了Python实现一个简单http服务器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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

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

代码实现

server.py

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

#!/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

1

2

3

4

5

6

7

8

9

<html>

 <head>

   <title>Python Server</title>

 </head>

 <body>

  <h1>Hello python</h1>

  <p>Welcom to the python world</br>

 </body>

</html>

测试

测试结果:

1

2

3

4

5

6

7

8

9

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实现随机调用一个浏览器打开网页

Python实现自定义顺序、排列写入数据到Excel的方法

以上就是Python实现简单http服务器的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python是面向对象的吗

详解Python使用回溯法子集树模板解决迷宫问题

Python如何进行进制转换

Python基于辗转相除法求解最大公约数的方法示例

Python queue模块

Python如何导入excel

Python中整数的最大可能值是多少?(代码示例)

Python如何解方程的三种方法

Python儿童编程有必要学吗

Python多线程socket编程中将多客户端接入的方法

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...