计算机网络基础socket programming代码

代码可以通过显示html的内容完成展示:
下面一段是socket programming部分:

#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
#Fill in start
serverHost = '192.168.109.49'##这里是我的IP(IPV4)地址,在cmd中舒服ipconfig/all来查看。
recvBuffer = 1024
serverPort = 80
serverSocket.bind((serverHost, serverPort))
serverSocket.listen(1)
print('the web server is up on port {}'.format(80))
#Fill in end
while True:
    #Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept() ##
    try:
        message = connectionSocket.recv(1024)  ##
        filename = message.split()[1]
        f = open(filename[1:])
        outputdata = f.read()##
        # print(outputdata)
        #Send one HTTP header line into socket
        #Fill in start
        connectionSocket.send('\nHTTP/1.1 200 OK\r\n\r\n'.encode())
        connectionSocket.send(outputdata.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])
        # connectionSocket.send("\r\n".encode())
        connectionSocket.close()
    except IOError:
        #Send response message for file not found
        print('\nWarning!\n the file do not exist in this folder!\n')
        #Fill in start
        connectionSocket.send('\n404 Not Found\n\n'.encode('utf-8'))
        #Fill in end
        #Close client socket
        #Fill in start
        serverSocket.close()
        #Fill in end
serverSocket.close()
sys.exit()#Terminate the program after sending the corresponding data

接下来是HelloWorld.html文件:

<!DOCTYPE html>
<html>
    <body>
        <p>Hello world!</p>
    </body>
</html>

展示:
将文件放入同一个文件夹下=>然后运行python程序,显示如下:
在这里插入图片描述
接下来在网页中输入:192.168.42.33:80/HelloWorld.html
在这里插入图片描述
如果输入一个错误的文件的话:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值