Socket Programming: Web Server

Socket Programming: Web Server

Experimental requirements

用Python语言开发一个简单的Web服务器,它仅能处理一个请求。具体而言,Web服务器将:
1.当一个客户(浏览器)联系时创建一个连接套接字;
2.从这个连接接受HTTP请求;
3.解释该请求以确定所请求的特定文件
4.从服务器的文件系统获得请求的文件;
5.创建一个由请求的文件组成的HTTP响应报文,报文前面有首部行;
6.经TCP连接向请求的浏览器发响应。
如果浏览器请求一个在该服务器中不存在的文件,服务器应当返回“404 Not Found”差错报文。

Web server programming code Socket


# import socket module
from socket import *  # 导入python套接字编程的库

serverSocket = socket(AF_INET, SOCK_STREAM)  # new一个TCP欢迎套接字
# Prepare a sever socket
serverSocket.bind(('', 1234))  # 将TCP欢迎套接字绑定到指定端口1234
serverSocket.listen(1)  # 设置服务器最大连接客户机数目为1

# 主体程序:服务器和客户机进行信息的交互
while True:
    # Establish the connection
    print ('Ready to serve...')
    connectionSocket, addr = serverSocket.accept();  # 建立一个TCP连接套接字,等待与客户端联系
    try:
        message = connectionSocket.recv(1024);  # 当建立了联系(accept()后),获取客户发送的报文
        filename = message.split()[1]
        f = open(filename[1:])
        outputdata = f.read();  # 从报文中读取信息
        # Send one HTTP header line into socket
        header = ' HTTP/1.1 200 OK\nConnection: close\nConnent-Type: text/html\nConnent-Length: %d\n\n' % (
            len(outputdata))
        connectionSocket.send(header.encode())

        # Send the content of the requested file to the client(将 Web服务器请求到的网页 返还给客户机)
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i].encode())

        connectionSocket.close()  # 关闭TCP连接套接字

    except IOError:
        # Send response message for file not found(如果连接建立失败:请求的文件找不到,则返回错误信息)
        header = ' HTTP/1.1 404 Not Found'
        connectionSocket.send(header.encode())

        connectionSocket.close()  # 关闭TCP连接套接字

serverSocket.close()  # 关闭TCP欢迎套接字

Web page requested by the client

Web pages and files to the server code files in the same folder below

<head> Hello World! </head>

He began to experiment

  • Open the code that runs in a Web server in Pycharm

  • Open your browser and port number written in the address bar before the server code and html file

    localhost:1234/HelloWorld.html
    

  • When you enter the wrong address in the browser address bar will return404 Not Found

Guess you like

Origin www.cnblogs.com/Weber-security/p/12661567.html