Python TCP 套接字:客户端和服务器套接字可以 运行 在同一线程上吗?

Python TCP sockets: can client and server sockets run on the same thread?

据我所知,套接字连接的客户端和服务器脚本不能在同一个程序(线程)中运行。但是下面的示例允许在套接字之间建立连接,甚至可以在同一程序(线程)中在它们之间交换消息。

谁能解释一下这里出了什么问题?

from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
import time

SERV_SOCK = socket(AF_INET, SOCK_STREAM)
SERV_SOCK.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
SERV_SOCK.bind(('localhost', 8888))
SERV_SOCK.listen()

CLIENT_SOCK = socket(AF_INET, SOCK_STREAM)
CLIENT_SOCK.connect(('localhost', 8888))

CLIENT_SOCK_SERV, ADDR = SERV_SOCK.accept()

TIMESTR = time.ctime(time.time()) + "\n"
CLIENT_SOCK_SERV.send(TIMESTR.encode('utf-8'))
TIME_BYTES = CLIENT_SOCK.recv(1024)
print(f"Current time: {TIME_BYTES.decode('utf-8')}")

time.sleep(1)
TIMESTR = time.ctime(time.time()) + "\n"
CLIENT_SOCK.send(TIMESTR.encode('utf-8'))
TIME_BYTES = CLIENT_SOCK_SERV.recv(1024)
print(f"Current time: {TIME_BYTES.decode('utf-8')}")

任何时候都不会考虑此代码 'blocking' 那么为什么它不起作用?

尽管服务器和客户端套接字在 python 中是可编程的,但所使用的套接字库正在通过系统可用的 API 调用底层系统。

The Python interface is a straightforward transliteration of the Unix system call and library interface for sockets to Python’s object-oriented style: the socket() function returns a socket object whose methods implement the various socket system calls. Parameter types are somewhat higher-level than in the C interface: as with read() and write() operations on Python files, buffer allocation on receive operations is automatic, and buffer length is implicit on send operations.

我强烈建议阅读 How-To on python sockets and python socket library references,因为它们将阻塞作为套接字的 3 种状态之一(阻塞、非阻塞和超时)