Python Web Socket AttributeError:type object' _socketobject'没有属性' gethostbyname'

时间:2016-03-01 15:30:40

标签: python sockets websocket attributeerror

第一次尝试使用python web套接字并坚持使用此错误:

AttributeError:type object' _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 OK\r\n\r\n')
        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()

另外,如果您有任何建议供图书馆使用,以使这更容易/更像您实际写的东西,我非常欣赏这些输入。

1 个答案:

答案 0 :(得分:0)

由于您将整个socket模块导入了命名空间,因此在调用socket.函数之前无需编写gethostname。像这样简化代码的第三行:serverSocket.bind((gethostname(), 80))