there are two types of client which will send messages to socket server.
for i in range(n):
client.send('1')
client.send('complete')
client.close()
for i in range(n):
client.connect(server)
client.send('2')
client.close()
client.connect(server)
client.send('complete')
client.close()
As a server how to listen 2 types client the same time ? The server need wait all client 'complete' then do someting.
I have tried to make server.linsten(1)
then start multi thread. if the server receive 'complete' then close thread. server will wait till thread count is 1 then do someting.
def continuous_receive():
try:
sock, addr = server.accept()
while 1:
data=sock.recv(1024).decode('utf8')
if not data:
sock.close()
sock, addr = server.accept()
else:
print(addr[0]+' '+data)
if data=='complete':
break
except:
print('wait client time out')
for i in range(client_count):
t=threading.Thread(target=continuous_receive)
t.start()
But it doesn't work well. the '2' client will crowd into the same thread and another thread will timeout.
Is there any other way can handle this?
use select
is a better solution,because there is a single thread can monitor the complete
count and break loop. code like:
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((ip, port))
server.listen(5)
inputs=[self.server]
outputs=[]
complete=0
while 1:
# 10 means block 10s/cycle
readable, writable, exceptional = select.select(inputs, outputs, inputs,10)
for s in readable:
if s is self.server:
sock,addr=s.accept()
inputs.append(sock)
else:
data=s.recv(1024).decode('utf8')
if data:
logging.info('%s %s'%(s.getpeername(),data))
else:
logging.info('%s disconnect'%(s.getpeername()[0]))
inputs.remove(s)
if data=='complete':
inputs.remove(s)
complete+=1
if complete==n:
self.server.close()
break