Python实现简单的HttpServer服务器


当前第2页 返回上一页

webServer.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

import socket

import sys

import getFileContent

#声明一个将要绑定的IP和端口,这里是用本地地址

server_address = ('localhost', 8080)

class WebServer():

  def run(self):

    print >>sys.stderr, 'starting up on %s port %s' % server_address

    #实例化一个Socket

    sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

    #绑定IP和端口

    sock.bind(server_address)

    #设置监听

    sock.listen(1)

    #这里首先给个死循环,其实这里是需要多线程的,再后续版本将会实现

    while True:

      #接受客户端的请求并得到请求信息和请求的端口信息

      connection, client_address = sock.accept()

      print >>sys.stderr, 'waiting for a connection'

      try:

        #获取请求信息

        data = connection.recv(1024)

        if data:

          #发送请求信息

          connection.sendall(getFileContent.getHtmlFile(data))

      finally:

        connection.close()

 

if __name__ == '__main__':

  server=WebServer()

  server.run()

webServer.py很清晰简洁,connection.sendall()服务端返回信息给浏览器,但是发送的数据必须遵循HTTP协议规范
getFileContent.py是对发送的数据进行HTTP协议规范处理


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

63

64

65

66

67

68

69

70

71

72

73

74

import sys

import os

 

#得到要发送的数据信息

def getHtmlFile(data):

  msgSendtoClient=""

  requestType=data[0:data.find("/")].rstrip()

  #判断是GET请求还是POST请求

  if requestType=="GET":

    msgSendtoClient=responseGetRequest(data,msgSendtoClient)

  if requestType=="POST":

    msgSendtoClient=responsePostRequest(data,msgSendtoClient)

  return msgSendtoClient

 

#打开文件,这里不直接写,二是去取要发送的文件再写

def getFile(msgSendtoClient,file):

    for line in file:

     msgSendtoClient+=line

    return msgSendtoClient

 

#筛选出请求的一个方法

def getMidStr(data,startStr,endStr):

  startIndex = data.index(startStr)

  if startIndex>=0:

    startIndex += len(startStr)

    endIndex = data.index(endStr)

    return data[startIndex:endIndex]

 

#获取要发送数据的大小,根据HTTP协议规范,要提前指定发送的实体内容的大小

def getFileSize(fileobject):

  fileobject.seek(0,2)

  size = fileobject.tell()

  return size

 

#设置编码格式和文件类型

def setParaAndContext(msgSendtoClient,type,file,openFileType):

  msgSendtoClient+="Content-Type: "+type+";charset=utf-8"

  msgSendtoClient+="Content-Length: "+str(getFileSize(open(file,"r")))+"\n"+"\n"

  htmlFile=open(file,openFileType)

  msgSendtoClient=getFile(msgSendtoClient,htmlFile)

  return msgSendtoClient

 

#GET请求的返回数据

def responseGetRequest(data,msgSendtoClient):

  return responseRequest(getMidStr(data,'GET /','HTTP/1.1'),msgSendtoClient)

 

#POST请求的返回数据

def responsePostRequest(data,msgSendtoClient):

  return responseRequest(getMidStr(data,'POST /','HTTP/1.1'),msgSendtoClient)

 

#请求返回数据

def responseRequest(getRequestPath,msgSendtoClient):

  headFile=open("head.txt","r")

  msgSendtoClient=getFile(msgSendtoClient,headFile)

  if getRequestPath==" ":

    msgSendtoClient=setParaAndContext(msgSendtoClient,"text/html","index.html","r")

  else:

    rootPath=getRequestPath

    if os.path.exists(rootPath) and os.path.isfile(rootPath):

      if ".html" in rootPath:

        msgSendtoClient=setParaAndContext(msgSendtoClient,"text/html",rootPath,"r")

      if ".css" in rootPath:

        msgSendtoClient=setParaAndContext(msgSendtoClient,"text/css",rootPath,"r")

      if ".js" in rootPath:

        msgSendtoClient=setParaAndContext(msgSendtoClient,"application/x-javascript",rootPath,"r")

      if ".gif" in rootPath:

        msgSendtoClient=setParaAndContext(msgSendtoClient,"image/gif",rootPath,"rb")

      if ".doc" in rootPath:

        msgSendtoClient=setParaAndContext(msgSendtoClient,"application/msword",rootPath,"rb")

      if ".mp4" in rootPath:

        msgSendtoClient=setParaAndContext(msgSendtoClient,"video/mpeg4",rootPath,"rb")

    else:

      msgSendtoClient=setParaAndContext(msgSendtoClient,"application/x-javascript","file.js","r")

  return msgSendtoClient

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

返回前面的内容

相关阅读 >>

Python如何保留2位小数

Python最详细之数据类型讲解

Python文件和流相关知识介绍

怎么安装Python解释器

Python使用struct处理二进制的方法详解

Python变量名有哪些

Python中range函数怎么用

高中要上Python

Python标准库有哪些

Python的链表数据结构讲解

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




打赏

取消

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

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

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

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

评论

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