栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

套接字编程作业之Web服务器(完整python代码)

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

套接字编程作业之Web服务器(完整python代码)

计算机网络自顶向下方法
套接字编程作业 Web服务器(单线程)
需求:

完整代码:

import time
# import socket module
from socket import *
import sys  # In order to terminate the program

serverSocket = socket(AF_INET, SOCK_STREAM)
# Prepare a sever socket
# Fill in start
severPort=6789
serverSocket.bind(('',severPort))
serverSocket.listen(1)
# Fill in end
while True:
    # Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept() # Fill in start #Fill in end
    message =  connectionSocket.recv(1024*1024).decode()# Fill in start #Fill in end/
    message = message.split()
    if len(message)<2:
        continue
    filename = message[1] #报文的第一个词是get,第二个词是文件位置
    try:
        f = open(filename[1:],"r",encoding='utf-8')   #文件位置以/开头
        # Fill in start
        outputdata = []
        size=0
        while True:
            s = f.read(1024)
            if len(s) == 0:
                break
            outputdata.append(s)
            size+=len(s)
            #Fill in end
        f.close()
        # Send one HTTP header line into socket
        # Fill in start
        head=""
        head+=message[2]
        head+=" 200 OKrn"
        head+="Connection: closern"
        head+="Date: "+time.strftime("%a, %d %b %Y %H:%M:%S GMT+8rn", time.localtime())
        head += "Server: liuxiangbin's laptoprn"
        # head+="Last-Modified: "+time.strftime("%a, %d %b %Y %H:%M:%S GMT+8rn", time.localtime())
        head+="Content-Length: "+str(size)+"rn"
        head+="Content-Type: text/htmlrnrn"
        connectionSocket.send(head.encode())
        # Fill in end
        # Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i].encode())
        connectionSocket.send("rn".encode())
        connectionSocket.close()
        # Send response message for file not found
        # Fill in start
    except FileNotFoundError:
        head=""
        head+=message[2]
        head+=" 404 Not Foundrn"
        head+="Connection: closern"
        head+="Date: "+time.strftime("%a, %d %b %Y %H:%M:%S GMT+8rn", time.localtime())
        head += "Server: liuxiangbin's laptoprn"
        # head+="Last-Modified: "+time.strftime("%a, %d %b %Y %H:%M:%S GMT+8rn", time.localtime())
        # head+="Content-Length: "+str(size)+"rn"
        head+="Content-Type: text/htmlrnrn"
        connectionSocket.send(head.encode())
    # Fill in end
    # Close client socket
    # Fi6ll in start
    connectionSocket.close()
    # Fill in end
serverSocket.close()
sys.exit()  # Terminate the program after sending the corresponding data
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/880650.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号