Skip to content Skip to sidebar Skip to footer

Python Socket Test Recv() Data

I have a problem with my python script using socket. I want to test if the client use the correct file, not an other tool like telnet. The server : import socket s = socket.socket(

Solution 1:

You can use select function to limit the time your server waits for new client connection or incoming data from client:

import socket
import select
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)

while1:

    # wait up to 60 seconds that a client connects
    newClient,_,_ = select.select([s], [], [], 60)

    ifnot (newClient):
        # no client wanted to connect  print'No new client in last 60 seconds!'returnelse:
        # new connection print'New client!'        
        conn, addr = s.accept()
        # wait up to 60 seconds that the client send data
        readable,_,_ = select.select([conn], [], [], 60)
        if (readable):
            data = conn.recv(1024)
            if data == 'test':
                print'ok'else:
                print'client do not send test'else:
            print'client send nothing'# close connection
        conn.close()

see select.

Post a Comment for "Python Socket Test Recv() Data"