0
0
PythonHow-ToBeginner · 3 min read

How to Receive Data from Socket in Python: Simple Guide

To receive data from a socket in Python, use the recv() method on a socket object, specifying the maximum number of bytes to read. This method waits for data from the connected socket and returns it as bytes.
📐

Syntax

The basic syntax to receive data from a socket in Python is:

  • data = socket.recv(buffer_size)

Here, socket is the connected socket object, and buffer_size is the maximum number of bytes to receive at once.

The method returns the received data as bytes. If the connection is closed, it returns an empty bytes object.

python
data = socket.recv(buffer_size)
💻

Example

This example shows a simple server that accepts a connection and receives data from a client using recv(). It prints the received message.

python
import socket

# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind to localhost on port 12345
server_socket.bind(('localhost', 12345))

# Listen for incoming connections
server_socket.listen(1)
print('Server listening on port 12345...')

# Accept a client connection
client_socket, addr = server_socket.accept()
print(f'Connected by {addr}')

# Receive data (up to 1024 bytes)
data = client_socket.recv(1024)

# Decode bytes to string and print
print('Received:', data.decode())

# Close sockets
client_socket.close()
server_socket.close()
Output
Server listening on port 12345... Connected by ('127.0.0.1', 54321) Received: Hello, server!
⚠️

Common Pitfalls

Common mistakes when receiving data from sockets include:

  • Not handling partial data: recv() may return less data than expected, so you might need to call it multiple times.
  • Not decoding bytes: Data received is bytes and must be decoded to string if needed.
  • Ignoring connection closure: recv() returns empty bytes when the connection is closed, which should be handled to avoid infinite loops.
python
import socket

# Wrong: Assuming recv returns all data at once
# data = client_socket.recv(1024)
# print(data.decode())

# Right: Loop to receive all data until connection closes
chunks = []
while True:
    chunk = client_socket.recv(1024)
    if not chunk:
        break
    chunks.append(chunk)
data = b''.join(chunks)
print(data.decode())
📊

Quick Reference

Tips for receiving data from sockets in Python:

  • Use recv(buffer_size) to read data.
  • Always check if recv() returns empty bytes to detect closed connections.
  • Decode bytes to string with data.decode() if needed.
  • For large data, loop and accumulate chunks until done.

Key Takeaways

Use socket.recv(buffer_size) to receive data from a connected socket in Python.
recv() returns bytes and may return less data than requested, so handle partial reads.
Check for empty bytes to detect when the connection is closed.
Decode bytes to string if you want to work with text data.
Loop to receive data in chunks for large or unknown-size messages.