【发布时间】:2015-02-14 23:00:29
【问题描述】:
我正在编写我的第一个 Python 套接字编程代码,但我不知道出了什么问题。我输入运行该程序的服务器的 IP 地址以及端口号和我尝试接收的文件。我应该在浏览器中接收文件并且套接字应该关闭。相反,服务器会打印 3 次打印行“Ready to serve...”,在浏览器上显示“404 Not Found”,并且从不关闭套接字。有人有什么想法吗?
#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()
【问题讨论】:
-
你怎么知道它永远不会关闭套接字?
-
尝试打印 IOError 异常对象,这可能会提供更多信息。您可能会从打开的文件中获取 IOError。 Python 2 还是 3?
-
我已经在 python 2.7.5 和 Windows Vista 中尝试过,它可以工作。
-
@rafalopez79 我使用的是 python 2.7.9。我正在访问的文件应该放在哪里?也许这是我的问题。
-
我正在测试它:127.0.0.1:12006/test.py 其中 test.py 是你的 python 脚本
标签: python sockets web websocket