Python Forum

Full Version: Array of Listening Sockets
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to figure out how to create a server. Here is what I want:

- Service port runs on port 5000
- Client connects to port and receives a random port in return.
- Server opens random listening port with 2 connections max
- Client disconnects from service port and reconnects on random port received.
- Remote client connects on random port as well and information is fwd between the 2 clients connected on that random port.

Issues:
I can get the service port working. I'm stuck at how to create an array of listening sockets generated on the fly as well as how to fwd info between only the 2 clients connected on each array. So if 6 clients connect there would be 6 different sockets with 2 clients on each. Information would only flow between 2 clients on each socket.

Here is what I have:

import socket, select

sock_config = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_config.bind(('0.0.0.0', 5000))
sock_config.listen(5)
config =

rlist = [sock_config]
wlist =
errlist =

out_buffer =


while True:
r, w, err = select.select(rlist, wlist, errlist)

for sock in r:
if sock == sock_config:
conf, addr = sock.accept()
config.append(conf)
rlist.append(conf)
else:
data = sock.recv(1024)
if data.find('[CONNECT]') != -1:
#Generate Random port or have a list of available ports.
#We will use 12345 for testing
sock.send("12345")
sock.close()
rlist.remove(sock)
else:
out_buffer.append(data)

out_string = ''.join(out_buffer)
out_buffer =

for sock in err:
sock.close()
rlist.remove(sock)

#for sock in w:
# print 'Test'

Any Help would be greatly appreciated. I am using Python 2.7
import socket, select

sock_config = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_config.bind(('0.0.0.0', 5000))
sock_config.listen(5)
config = []    

rlist = [sock_config]
wlist = []
errlist = []

out_buffer = []


while True:
	r, w, err = select.select(rlist, wlist, errlist)
	
	for sock in r:
		if sock == sock_config:
			conf, addr = sock.accept()
			config.append(conf)
			rlist.append(conf)
		else:
			data = sock.recv(1024)
			if data.find('[CONNECT]') != -1:
				#Generate Random port or have a list of available ports.
				#We will use 12345 for testing
				sock.send("12345")
				sock.close()
				rlist.remove(sock)
			else:
				out_buffer.append(data)

		out_string = ''.join(out_buffer)
		out_buffer = []

	for sock in err:
		sock.close()
		rlist.remove(sock)
		
	#for sock in w:
	#	print 'Test'