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

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

接着在此文件夹下,编写一个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文件,在浏览器中输入网址,即可访问。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值