Reputation: 71
How to create multi-server sockets on one client in Python ? I am thinking about create a List of server socket and make the connection with non-blocking socket, but i don't find a good tutorial for that, thats why i came here, to ask for better solution or a guide for non-blocking socket.
Thank you !
Thank for the help, but i mean to something different, i have list of Servers Ip like that:
SERVER_IP = ['127.0.0.1', '127.0.0.2', '127.0.0.3', '127.0.0.4', '127.0.0.5', '127.0.0.6, '127.0.0.7']
I have one option to create a list of sockets by ip, and try to connect to every Ip Server, but i ask here if i have a different way to connect to all this Servers Ip without a list of sockets, something more convenient.
Thank you.
Upvotes: 2
Views: 7031
Reputation: 412
If you want to have multiple sockets connected to multiple servers, you should check out the select
module (http://docs.python.org/2/library/select.html).
Basically, it works like this:
import socket, select
socks = {}
# Connect to different servers here #
sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks[sock1.fileno()] = sock1
poll = select.poll()
for sock in socks:
poll.register(sock)
while 1:
fd, event = poll.poll() # Optional timeout parameter in seconds
sock = socks[fd]
sock.recv(1024) # Do stuff
A note, the poll.poll()
method returns the underlying file number (what your operating system uses to represent files) which is useless to you. I just stores the sockets in a dictionary by that number so you could get the actual socket object from the filenumber that is given by poll. I recommend reading the documentation for select.poll, the link above.
Upvotes: 3
Reputation: 8620
You can use select
.
http://pymotw.com/2/select/ plus the select
documentation.
Or some third party module such as twisted
.
Upvotes: 2