Python 2.7: Listen to requested connections + listen to already established connections at the same time

I am currently trying to make a chatroom server. I'm trying to make it so I can listen for new requested connections and listen for messages sent from already established connections at the same time.

I can use this to listen for requested connections:

def reqlisten():
    global hostlist
    while True:
        conn, address = (sock.accept)
        hostlist.append(conn)
        print 'Recieved connection form', address

And I can use this to listen messages sent from already established connections:

def meslisten():
    global hostlist
    while True:
        ready_socks,_,_ = select.select(hostlist, [], [])
        for sock in ready_socks:
            data, addr = sock.recvfrom(255)
            print 'Received message:', data
            broadcast(message)
            print 'Broadcasting message.'

But how do I do both of these at the same time?

Upvotes: 2

Views: 60

Answers (1)

cmidi
cmidi

Reputation: 2010

There are multiple ways to do this.

  1. One easy way is to accept one connection at a time and receive on a accepted socket for a fixed amount by setting the sockets to be non-blocking asynchronously.

Below is an example code to do that.

hostlist = []
def Accept(sock):
    ##Accept one connection at a time                                                                                                                                                                                                        
    conn,address = sock.accept()
    print "accept",address
    conn.setblocking(0)
    hostlist.append(conn)

def Recv(sock):

    data,addr = sock.recvfrom(255)
    print "recv",data

if __name__ == "__main__":
    listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listen_socket.bind((socket.gethostname(),4041))
    listen_socket.setblocking(0)
    listen_socket.listen(5)
    hostlist.append(listen_socket)
    while True:
        ready_socks,_,_ = select.select(hostlist, [], [])
        for sock in ready_socks:
            if sock == listen_socket:
                Accept(sock)
            else:
                Recv(sock)

Upvotes: 1

Related Questions