Problem:
Python's socket.recv() method doesn't return data when called a second time after editing the echo server code to avoid sending data back to the client.
Analysis:
TCP sockets operate as streams of data, lacking a one-to-one correlation between send and receive calls. The initial code adhered to a specific protocol where the server sent back exactly what it received until the client closed the connection.
The modification altered the rules, causing the server to continuously receive and discard data without responding until the client closed their end. The client, expecting an immediate response, hangs indefinitely.
Solution:
To resolve this issue, the client must adjust its behavior to match the modified server protocol.
Client Modification:
Close the outgoing side of the socket to signal completion, allowing the server to send the response. Implement multiple recv() operations to handle potential data fragmentation.
import socket HOST = 'localhost' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.sendall(b'Hello, world') s.shutdown(socket.SHUT_WR) data = b'' while True: buf = s.recv(1024) if not buf: break data += buf s.close() print('Received', repr(data))
Updated Server Code:
Maintain the altered protocol, sending "ok" once the client closes their incoming connection.
import socket HOST = '' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print('Connected by', addr) while True: data = conn.recv(1024) if not data: break conn.sendall(b'ok') conn.shutdown(socket.SHUT_WR) conn.close()
The above is the detailed content of Why Doesn\'t My Python Socket Receive Data After the First `recv()` Call Unless I Modify the Client?. For more information, please follow other related articles on the PHP Chinese website!