Python socket test recv() data -


i have problem python script using socket. want test if client use correct file, not other tool telnet. server :

import socket s = socket.socket(socket.af_inet, socket.sock_stream) s.bind((host, port)) s.listen(1) while 1:     conn, addr = s.accept()     data = conn.recv(1024)     if data == 'test':         print 'ok'     else:         print '!'         conn.close() 

the client:

import socket s = socket.socket(socket.af_inet, socket.sock_stream) s.connect(host, port) s.send('test') 

the client send 'test' server verify it's correct file. in case client send nothing (if client uses way connect), can't test if conn.recv(1024) equals 'test' because script freezes, need wait client stop , server unfreezes. thank in advance.

you can use select function limit time server waits new client connection or incoming data client:

import socket import select s = socket.socket(socket.af_inet, socket.sock_stream) s.bind((host, port)) s.listen(1)  while 1:      # wait 60 seconds client connects     newclient,_,_ = select.select([s], [], [], 60)      if not (newclient):         # no client wanted connect           print 'no new client in last 60 seconds!'         return     else:         # new connection          print 'new client!'                 conn, addr = s.accept()         # wait 60 seconds client send data         readable,_,_ = select.select([conn], [], [], 60)         if (readable):             data = conn.recv(1024)             if data == 'test':                 print 'ok'             else:                 print 'client not send test'         else:             print 'client send nothing'          # close connection         conn.close() 

see select.


Comments