Search code examples
pythonsocketswait

Python socket sends a message to the Client after no data received in 5 seconds


A way for python socket to send for example: "Timeout" to the client if client hasn't sent anything in for example 5 seconds and then close the connection(I can do the connection closing which would be c.close() but that is as far as I know in this situation)? I'm a beginner when it comes to more advanced socket programming like this. I don't know what to try so can't send a "what Ive tried" code. All I can send is my current code for the server.

import socket
from random import *
s = socket.socket()
s.bind(("localhost",int(input("Port\n>>> "))))
s.listen(1)
while True:
    c,a = s.accept()
    data = c.recv(1024)
    #Somewhere here, it would wait for 5 sec for a message to come and if not then:
    c.send("Timeout".encode())
    c.close()

Solution

  • just set a timeout?

    s.settimeout(5.0)
    data = c.recv(1024)
    if(not data):
       c.send(b"Timeout")
       c.close()