2

I want to set up tcp server and client where server monitors client input and sends a request every 3 seconds if no input is received. Then client replies with its time. This goes on in an infinite loop. Also, they both have an option to exit the infinite loop. I don't know how to add the exit functionality as send(), recv() and input() block the code execution.

I have tried using select with 3 second timeout, it didn't work. I have tried threading but it stops after first user input until the next user input. I want it to go infinitely unless user wants to exit.

Infinite loop for communication:

client side:

while True:
    data = ClientSocket.recv(1024).decode()
    print("From Server: " + str(data))
    # clear string
    data = ''
    data = 'Random Number: ' + str(random.randint(1, 101))
    current_time = datetime.now()
    required_format = (current_time.strftime("Date: %Y-%m-%d\tTime: %H:%M:%S.%f")[:-3])
    data = data + "\t" + required_format + '\n'
    ClientSocket.send(data.encode())
    print("Sending: " + str(data))
    data = ''

Server Side:

while True:
    data = ''
    data = 'Please enter a response.'
    print("Sending: " + str(data))
    ClientSocket.send(data.encode())
    # clear string
    data = ''
    data = ClientSocket.recv(1024).decode()
    print("From Client: " + str(data))

Select function that i tried:

readlist = [ClientSocket]

incoming = select.select(readlist, [], [], 3)

if incoming:
    #perform a chat function here

else:
         #use the code mentioned above for automated messages

This is the threading feature that I tried: Python 3 Timed Input

How can I restrict time for recv(), send() and input() while sending and receiving message request and acknowledgements?

Please let me know if you would like to see the full code.

Abhishek
  • 23
  • 3

1 Answers1

0

Something like this should work for you

server.py

inputs = [server]
outputs = []
messages = {}


try:
    while inputs:
        readable, writable, error = select.select(inputs, outputs, [])

        for sock in readable:
            if sock is server:
                client, _ = sock.accept()
                inputs.append(client)
                messages[client] = Queue()
            else:
                data = sock.recv(1024).decode()
                if data and data != 'exit\n':
                    print(data)
                    messages[sock].put(data)
                    if sock not in outputs:
                        outputs.append(sock)
                else:
                    print('Client disconnected')
                    sock.close()
                    inputs.remove(sock)
        for sock in outputs:
            try:
                msg = messages[sock].get_nowait()
                sock.send(msg.upper().encode())
            except Empty:
                sleep(3)
                sock.send(b'No data recieved')
                outputs.remove(sock)


except KeyboardInterrupt:
    server.close()

client.py

inputs = [sock, sys.stdin]

while inputs:
    readable, _, _ = select.select(inputs, [], [])

    for s in readable:
        if s is sock:
            data = sock.recv(1024).decode()
            if data:
                if data.lower() != 'exit':
                    print('{}'.format(data))
                    sys.stdout.write('You: ')
                    sys.stdout.flush()
                else:
                    exiting('Server')
            else:
                exiting('Server')
        else:
            msg = sys.stdin.readline()
            sock.send(msg.encode())
            sys.stdout.write('You: ')
Rohit
  • 2,118
  • 14
  • 35