Manage a Local Stream Socket Lifecycle
Core idea
A TCP server normally binds, listens and accepts a connected socket; a client connects to it. Each connected stream carries bytes, not messages. sendall sends the supplied bytes or raises; recv reads up to a requested size. A local socketpair demonstrates exchange without opening a listening port. Set timeouts and close both ends.
import socketa, b = socket.socketpair()with a, b: a.settimeout(1); b.settimeout(1) a.sendall(b'hello') a.shutdown(socket.SHUT_WR) parts = [] while chunk := b.recv(2): parts.append(chunk) print(b''.join(parts).decode())The write shutdown lets the receiver observe EOF after buffered bytes.
Exchange a short acknowledgement
import socketa, b = socket.socketpair()with a, b: a.settimeout(1); b.settimeout(1) a.sendall(b'?') if b.recv(1) == b'?': b.sendall(b'!') print(a.recv(1))print(a.fileno() == -1, b.fileno() == -1)The one-byte protocol avoids message-boundary assumptions; both descriptors close.
Common mistake
One recv call may return fewer bytes than requested. Use explicit framing or EOF as appropriate; never wait indefinitely for an assumed complete message.
Practice
Change the first payload and receive size, then verify the reconstructed bytes stay identical.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Socket lifecycle
Check your understanding of socket lifecycle.
What is printed?
import socketa,b=socket.socketpair()with a,b: a.shutdown(socket.SHUT_WR) print(b.recv(1))What is printed?
import socketa,b=socket.socketpair()with a,b: a.settimeout(2) print(a.gettimeout())What does recv(1024) promise?
Which server action obtains a connected socket?