blocking socket

Blocking socket calls recv to get no data:

  • If no timeout is set, this blocks forever until there is data
  • If the timeout time is set and no data is received within the specified time, a TimeoutError exception will be thrown. This exception is a built-in exception of Python, which does not depend on a third party, and does not only need to import packages. It can be used directly.

Set the timeout method:

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('127.0.0.1', 8080))

clientsocket.settimeout(3.0)
data = clientsocket.recv(2024)
clientsocket.close()
data.decode()

The result is as follows:

Traceback (most recent call last):
  File "/home/bot/Desktop/coder/ideaboom/test_socket/main.py", line 7, in <module>
    data = clientsocket.recv(2024)
TimeoutError: timed out

Reference article:
tcp buffer full problem
How to set timeout on python's socket recv method?

non-blocking socket

Non-blocking socket calls recv to get no data:

  • Immediately return the error: BlockingIOError: [Errno 11] Resource temporarily unavailable, where BlockingIOError is a built-in Python exception, no need to import packages and rely on third parties

Example:

import socket  # 客户端 发送一个数据,再接收一个数据
from socket import socket as Socket


clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

clientsocket.connect(('127.0.0.1', 8080))
clientsocket.setblocking(False)

data = clientsocket.recv(2024)

clientsocket.close()

The result is as follows:

Traceback (most recent call last):
  File "/home/bot/Desktop/coder/ideaboom/test_socket/main.py", line 10, in <module>
    data = clientsocket.recv(2024)
BlockingIOError: [Errno 11] Resource temporarily unavailable

universe_king
3.4k 声望680 粉丝