计算机网络基础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

如果输入一个错误的文件的话:

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐



所有评论(0)