[Python2.7]套接字连接问题

时间:2016-10-19 22:28:51

标签: python python-2.7 sockets

我在python 2.7中创建一个套接字聊天服务器但是我无法使用我的客户端连接到服务器我收到此错误:

文件" ChatClientV2.py",第46行,in     read_sockets,write_sockets,error_sockets = select.select(socket_list,[],[]) select.error:(10038,'尝试对非套接字的操作')

我不知道为什么我得到这个错误我需要帮助这个这是我用于客户端的代码和一些额外的东西之后但我不想被代码量限制所以我没有发布所有这些

import socket, select

#Function to broadcast chat messages to all connected clients
def broadcast_data (sock, message):
    #Do not send the message to master socket and the client who has send us the   message
    for socket in CONNECTION_LIST:
        if socket != server_socket and socket != sock :
            try :
                socket.send(message)
            except :
                # broken socket connection may be, chat client pressed ctrl+c for example
                socket.close()
                CONNECTION_LIST.remove(socket)

if __name__ == "__main__":

# List to keep track of socket descriptors
CONNECTION_LIST = []
RECV_BUFFER = 4096 # Advisable to keep it as an exponent of 2
PORT = 5000

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# this has no effect, why ?
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("192.168.0.8", PORT))
server_socket.listen(10)

# Add server socket to the list of readable connections
CONNECTION_LIST.append(server_socket)

print "Chat server started on port " + str(PORT)

while 1:
    #print CONNECTION_LIST
    # Get the list sockets which are ready to be read through select
    read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])
     for sock in read_sockets:
         #New connection
         if sock == server_socket:
             # Handle the case in which there is a new connection recieved through server_socket
             sockfd, addr = server_socket.accept()
             CONNECTION_LIST.append(sockfd)
             #print "Client (%s, %s) connected" % addr

             broadcast_data(sockfd, "entered room\n")

        #Some incoming message from a client
        else:
            # Data recieved from client, process it
            try:
                #In Windows, sometimes when a TCP program closes abruptly,
                # a "Connection reset by peer" exception will be thrown
                data = sock.recv(RECV_BUFFER)
                if data:
                    #broadcast_data(sock, "\r" + '<' + str(sock.getpeername()) + '> ' + data)
                    broadcast_data(sock, "\r" + data)

            except:
                broadcast_data(sock, "Client (%s, %s) is offline" % addr)
                print "Client (%s, %s) is offline" % addr
                sock.close()
                CONNECTION_LIST.remove(sock)
                continue

server_socket.close()

0 个答案:

没有答案