Harvey
Harvey

Reputation: 1418

Python socket select.select. Using list of objects instead of connections

Typically using select.select() will require a list of connection objects to work like this:

read, write, error = select(self.all_connections, [], [], 0.1)

Say I have the below object:

class remoteDevice(object)

    def __init___(self, connection):
        self.connection = connection

I will create a list of remoteDevices before using select after accepting the connections and append them to a list:

conn  = socket.accept()
newDevice = remoteDevice(conn)
all_devices.append(newDevice)

Now all_devices will be alist of multiple devices, and their connection object is given to each remote device.

Is there a way I can pass in all_devices into the select statement to iterate through the connection property of each remoteDevice object? Will I have to store the connection objects seperately just to use select.select()?

Upvotes: 2

Views: 1712

Answers (1)

mhawke
mhawke

Reputation: 87124

According to the select.select() documentation you can supply a sequence of objects that have a fileno() method. You can easily add that method to your class:

class RemoteDevice(object):
    def __init__(self, connection):
        self.connection = connection

    def fileno(self):
        return self.connection[0].fileno()

The fileno() method simply returns the file descriptor of the connection's socket object. Since you instantiate RemoteDevice with the return value of socket.accept(), this a tuple in which the first item is a socket object.

Upvotes: 5

Related Questions