Python Socket | How To Set Socket Timeout – Sometimes, you need to manipulate the default values of certain properties of a socket
library, for example, the socket timeout.You can make an instance of a socket object and call a gettimeout() method to get the
default timeout value and the settimeout() method to set a specific timeout value. This is
very useful in developing custom server applications. We first create a socket object inside a socket_time_out() function. Then, we can
use the getter/setter instance methods to manipulate timeout values.
Also you can check Python Socket Programming Articles
1: Python Socket Programming How To Create Socket
2: Python Socket How To Get Local Machine IP Address
3: Python Socket How To Get Website IP Address
4: Python Socket How To Connect TCP Client To Server
5: Python Socket How To Convert IPv4 Address
So now this is the complete code for Python Socket | How To Set Socket Timeout
1 2 3 4 5 6 7 8 9 10 11 12 |
import socket def socket_time_out(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('Default Socket Timeout', s.gettimeout(), s.settimeout(100)) print('Current Socket Timeout', s.gettimeout()) socket_time_out() |
So now run the complete code and this will be the result
How it works
In this code snippet, we have first created a socket object by passing the socket family and
socket type as the first and second arguments of the socket constructor. Then, you can
get the socket timeout value by calling gettimeout() and alter the value by calling the
settimeout() method. The timeout value passed to the settimeout() method can be in
seconds (non-negative float) or None. This method is used for manipulating the blocking-socket operations. Setting a timeout of None disables timeouts on socket operations.
Also you can watch the complete video for this article
Subscribe and Get Free Video Courses & Articles in your Email