为什么这个attributeError会一直出现,我如何解决这个问题

时间:2015-11-10 09:44:18

标签: python sockets

当我运行聊天程序时,始终存在属性错误。 有人可以解释为什么我的代码中出现此错误并建议解决方案。 聊天程序是

import socket
import select
import sys
#list for socket descriptors
socket_list = []
host = socket.gethostname()
port = 5009
def chat_server():
    server_socket = socket.socket(socket.AF_INIT, socket.SOCK_DGRAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind((host, port))
    server_socket.listen(10)

    # add server socket to the list
    socket_list.append(server_socket)

    print "chat server started on port" + str(port)

    while 1:
        #get the list of sockets to be read through select
        read, write, error = select.select(socket_list, [], [])
        for sock in read:
            if sock == server_socket:
                sock_obj, addr = server_socket.accept()
                socket_list.append(sock_obj)
                print "Client (%s, %s) connected"%addr)
                broadcast(srver_socket, sock_obj,
                      "[%s, %s] entered our chat address" %addr)
            else :
                #process data recieved from client,
                data = sock.recv(4000)
                if data :
                    broadcast(server_socket0, sock,
                          'Message[' + addr[0] + ':'
                           + str(addr[1]) + '] -' + data.strip())
                else :
                    # remove the broken socket
                    if sock in socket_list :
                        socket_list.remove(sock)
                    broadcast(server_socket, sock,
                          "Client (%s, %s) is offline" %addr)

    server_socket.close()

# broadcast the messages to our clients
def broadcast (server_socket, sock, msg):
    for sockets in socket_list :
        if sockets != server_socket and sockets != sock :
            socket.send(msg)

当我运行此代码时,会发生以下错误, 请提出一些建议,使其正确

Traceback (most recent call last):
  File "chat_server.py", line 55, in <module>
    chat_server()
  File "chat_server.py", line 11, in chat_server
    server_socket = socket.socket(socket.AF_INIT, socket.SOCK_DGRAM)
AttributeError: 'module' object has no attribute 'AF_INIT'

1 个答案:

答案 0 :(得分:1)

您使用的是哪个版本,未找到socket.AF_INIT

socket.AF_INET存在于python 2.7版本(https://docs.python.org/2/library/socket.html