第一次
尝试python web套接字并坚持这个错误:
属性错误:类型对象"_socketobject"没有属性"gethostbyname"
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((socket.gethostname(), 80))
serverSocket.listen(5)
while True:
print 'Ready to serve.'
connectionSocket, addr = serverSocket.accept()
print 'connection is from', addr
try:
message = connectionSocket.recv(2048)
filename = message.split()[1]
print filename
f = open(filename[1:])
outputdata = f.read()
connectionSocket.send('HTTP/1.1 200 OKrnrn')
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
print 'IOError'
connectionSocket.send('HelloWorld.html')
connectionSocket.close()
serverSocket.close()
另外,如果您对库有任何建议,以使其更容易/更像您实际编写的内容,我将非常感谢您的输入。
由于您将整个socket
模块导入到命名空间中,因此无需在调用gethostname
函数之前编写socket.
。简化代码的第三行,如下所示:serverSocket.bind((gethostname(), 80))