TCP Modes Flashcards
What are the three socket modes?
Blocking, non-blocking, and timeout. Blocking waits indefinitely, non-blocking returns errors if operations can’t complete immediately, and timeout raises exceptions after a specified duration.
What is the default socket mode and timeout?
Sockets are created in blocking mode by default with a timeout value of None
(no timeout). Use getdefaulttimeout()
to check.
How does setdefaulttimeout()
differ from socket.settimeout()
?
setdefaulttimeout()
sets the global timeout for new sockets. socket.settimeout()
sets a timeout for a specific socket without affecting the global default.
What does gettimeout()
return for each socket mode?
- Blocking:
None
<br></br>- Non-blocking:0
<br></br>- Timeout: A positive float (timeout duration in seconds).
How does the connect()
method behave in terms of timeout?
connect()
always operates in timeout mode. The timeout can be set using socket.settimeout()
before calling connect()
.
What determines the mode of the socket returned by accept()
?
The defaulttimeout
value:<br></br>- If defaulttimeout
is positive: Returned socket uses timeout mode.<br></br>- If defaulttimeout
is 0
: Non-blocking.<br></br>- If defaulttimeout
is None
: Mode matches the listening socket (blocking/timeout) or is OS-dependent (non-blocking).
Which socket methods are always blocking regardless of mode?
socket()
, bind()
, and connect()
(though connect()
behaves as timeout).
What happens in non-blocking mode if an operation can’t complete immediately?
The method returns an error (e.g., BlockingIOError
) instead of waiting.
How to configure a socket to raise TimeoutError
after 5 seconds?
Use socket.settimeout(5.0)
to set a per-socket timeout or setdefaulttimeout(5.0)
for global configuration.
What is the purpose of SO_LINGER
in the close()
method?
It configures whether close()
blocks to ensure data is sent. By default, close()
is non-blocking unless SO_LINGER
is set.
How does the create_connection()
method handle timeouts?
It uses the timeout
parameter (defaults to getdefaulttimeout()
). If the default is non-positive, the OS assigns a timeout.
What error message does the time_client
example print for a connect timeout?
time(client): connect timeout
if the connection exceeds the 3-second timeout.
How to differentiate blocking and timeout modes using getblocking()
?
getblocking()
returns True
for blocking and timeout modes (since timeout is a subtype of blocking), and False
for non-blocking.
What exception is raised when a timeout expires during recv()
?
TimeoutError
(e.g., time(client): no response from server
in the example).
Why might fixed-size messaging be inefficient for TCP?
TCP already handles fragmentation; adding fixed-size messages duplicates this effort (“TCP over TCP”), increasing overhead.