python练习20 -- fork函数实现web服务器

python源代码httpd.py:

#!/bin/env python3

from socket import *
import os
import signal

HOST = "0.0.0.0"
PORT = 80


MSG = """HTTP/1.1 200 OK
Content-Type: text/html


"""

MSG404 = """HTTP/1.1 404 NOT FOUND
Content-Type: text/html


<html>
<h1>
Sorry No Web Page for You!!!!
</h1>
</html>
"""

def handle( c):
    while True:
        bs = c.recv(1024)
        if not bs:
            break
        data = bs.decode()
        request = data.split('\n')[0]
        print("request = ", request)
        data =  request.split()[1]
        if data == "/":
            with  open("index.html") as f:
                msg = MSG + f.read()
        else:
            filename = data.split("/")[1]
            if os.path.exists(filename):
                with open(filename) as f:
                    msg = MSG + f.read()
            else:
                    msg = MSG404


        c.send(msg.encode())
    c.close()
    print()

def server():
    print("listen on port %d" % PORT)
    sock = socket(AF_INET, SOCK_STREAM)
    sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    sock.bind((HOST, PORT))
    sock.listen(5)
    signal.signal(signal.SIGCHLD, signal.SIG_IGN)

    while True:
        try:
            c, addr = sock.accept()
            print("connect from ", addr)
        except KeyboardInterrupt:
            os._exit(-1)
        except Exception as e:
            print(e)
            continue

        pid = os.fork()

        if pid == 0:
            sock.close()
            handle(c)
            os._exit(0)
        elif pid > 0:
            c.close()
        else:
            pass


if __name__ == "__main__":
    server()

在与httpd.py相同目录下准备两个html文件:index.html和c1.html

<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome index</title>
</head>
<body>
<h1></h1>
<div>
    <p>
        This is a Test Page
    </p>
</div>
</body>

</html>

<!--c1.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试网页c1</title>
</head>
        <style>
                div {
                        font-size:20px;
                        color: blue;
                }
        </style>
<body>
        <div >
                <h1>锦瑟</h1>
                <p style="font-size:25px">锦瑟无端五十弦,一弦一柱思华年。</p>
                <p style="color:red">庄生晓梦迷蝴蝶,望帝春心托杜鹃。</p>
                <p>沧海月明珠有泪,蓝田日暖玉生烟。</p>
                <p>此情可待成追忆,只是当时已惘然。</p>
        </div>
</body>
</html>

客户端测试:

运行httpd.py

测试浏览器chrome:分别访问index.html, c1.html以及一个不存在的abc.html,结果如下:

 

服务器端连接信息:

[root@gyl-ali python3]# ./httpd.py
listen on port 80
connect from  ('61.87.242.101', 63505)
connect from  ('61.87.242.101', 63506)
request =  GET /abc.html HTTP/1.1
request =  GET /index.html HTTP/1.1

connect from  ('61.87.242.101', 63588)
request =  GET /c1.html HTTP/1.1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值