Home > Backend Development > Python Tutorial > Why Doesn\'t My Python Socket Receive Data After the First `recv()` Call Unless I Modify the Client?

Why Doesn\'t My Python Socket Receive Data After the First `recv()` Call Unless I Modify the Client?

Susan Sarandon
Release: 2024-11-28 20:10:16
Original
558 people have browsed it

Why Doesn't My Python Socket Receive Data After the First `recv()` Call Unless I Modify the Client?

Python Socket not Receiving Data Without Sending

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.

  • Updated Client Code:
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))
Copy after login
  • 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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template