1

I have a neat little program here that just connects to servers. It is a UDP client. It is supposed to send a message to the server and wait for the response.

import socket

host = socket.gethostname() # Change to the ip address 
port  = 4000

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
message = input('Send_To_Server: ')

while message != 'endhost':
     s.sendto(message.encode('utf-8'), (host, port))
     data, addr = s.recvfrom(1024)
     data = data.decode('utf-8')
     print("Received from server: " + data)
     message = input('Send_To_Server: ')
s.close()

The only problem is that if the server is not up, it just sits there. Is there any way to set a timeout so after so many seconds it goes over the command?

1

1 Answer 1

0

Use the settimeout function :

import socket

host = socket.gethostname() # Change to the ip address 
port  = 4000

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(10)
message = input('Send_To_Server: ')

while message != 'endhost':
     s.sendto(message.encode('utf-8'), (host, port))
     data, addr = s.recvfrom(1024)
     data = data.decode('utf-8')
     print("Received from server: " + data)
     message = input('Send_To_Server: ')
s.close()

This will set a 10s timeout.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.