Python套接字编程简单Web

2024-04-25 16:41:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写我的第一个Python socket编程代码,我无法找出哪里出了问题。我键入运行此程序的服务器的IP地址,以及端口号和试图接收的文件。我应该在浏览器中收到文件,并且套接字应该关闭。相反,服务器会打印三次打印行“准备就绪…”,在浏览器上显示“404未找到”,并且从不关闭套接字。有人有什么想法吗?

#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverSocket.bind(('', 12006))
serverSocket.listen(1)
while True:
    print 'Ready to serve...'
    #Establish the connection
    connectionSocket, addr = serverSocket.accept()
    try:
        message = connectionSocket.recv(1024)
        filename = message.split()[1]
        f = open(filename[1:])
        outputdata = f.read()
        f.close()
        #Send one HTTP header line into socket
        connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n')
        #Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i])
        connectionSocket.close()
    except IOError:
        #Send response message for file not found
        connectionSocket.send('404 Not Found')
        #Close client socket
        connectionSocket.close()
serverSocket.close() 

Tags: 文件thetoimport服务器sendmessageclose
1条回答
网友
1楼 · 发布于 2024-04-25 16:41:05

谢谢大家的帮助。我知道怎么了。我将HTML重命名为“HelloWorld.HTML”,然后Windows自动将.HTML添加到文件末尾。所以为了访问这个文件,我需要输入HelloWorld.html.html。我更改了文件名,然后这段代码运行得很好。

相关问题 更多 >