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?

cyberpig.908
  • 23
  • 1
  • 5
  • Does this answer your question? [How to set timeout on python's socket recv method?](https://stackoverflow.com/questions/2719017/how-to-set-timeout-on-pythons-socket-recv-method), [python udp client time out machinsm](https://stackoverflow.com/questions/18311338/python-udp-client-time-out-machinsm), [Handling a timeout error in python sockets](https://stackoverflow.com/questions/11865685/handling-a-timeout-error-in-python-sockets) – Steffen Ullrich Jul 23 '20 at 04:25

1 Answers1

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.

Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40