计算机网路自顶向下套接字web服务器

首先试验能否在主机上ping通虚拟机,在ping通后,在某一文件夹下用vim编写一个html文件

计算机网路自顶向下套接字web服务器_第1张图片

接着在此文件夹下,编写一个webServer.py

#!/usr/bin/env python
#import socket module
from socket import *
import sys

serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverPort = 6780
serverSocket.bind(("", serverPort))
serverSocket.listen(1)
while True:
    #Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept()
   # print(addr)
    try:
        message = connectionSocket.recv(1024)
        #print(message)
        #print(len(message))
        filename = message.split()[1]
        #print('%s'%filename)
        #print(filename[1:].decode())
        f = open(filename[1:])
        outputdata = f.read()
        header='HTTP/1.1 200 OK\nConnection:keep-alive\nContent-type: text/html\nContent-Length: %d\n\n'%(len(outputdata))
        connectionSocket.send(header.encode())
        #Send one HTTP header line into socket
        #Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i].encode())
        connectionSocket.close()
        print("OK!")
    except IOError:
        #Send response message for file not found
        outputdata = 'HTTP/1.1 404 Not Found\r\n\r\n'
        #Close client socket
        connectionSocket.send(outputdata.encode())
        connectionSocket.close()
serverSocket.close()
                       

 运行py文件,在浏览器中输入网址,即可访问。

你可能感兴趣的:(计算机网络,服务器,python,运维)