简体   繁体   中英

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

As far as I know, client and server script for socket connection cannot be run in the same program (thread). But the example below allows to establish a connection between sockets and even exchange messages between them in the same program (thread).

Can anyone please explain what is wrong here?

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')}")

At no point is any of this code considered 'blocking' so why wouldn't it work?

Though the server and client sockets are programmable in python the sockets library used is making calls to the underlying system via the systems available APIs.

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.

I would strongly recommend reading the How-To on python sockets and python socket library references as they cover blocking as one of the 3 states of a socket (blocking, non-blocking and timeout)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM