Python Sockets: Build a TCP Client

Updated on: August 20, 2026
Reading time: 3 minutes
Criação de cliente TCP simples usando Python

Building a simple TCP client in Python is one of the fundamental steps for anyone who wants to understand how the internet works under the hood. TCP (Transmission Control Protocol) is the foundation of nearly everything we do online, from browsing websites to sending instant messages. In this guide you will learn how to establish a network connection using Python’s built-in socket module, with no external libraries required.

What is a TCP client?

Think of the client-server architecture like a phone call: the server is waiting for the phone to ring, while the client is the one making the call. A TCP client initiates the conversation by requesting a connection to a specific IP address and port. Unlike UDP, TCP is connection-oriented: it guarantees that data arrives in the correct order and without errors, automatically requesting retransmission if a packet is lost.

Python manages this interaction through the socket module, which provides an interface to the Berkeley socket API. This is the industry standard for network communications across Linux, Windows, and macOS. The official Python socket documentation covers the complete API reference.

Step 1: Define the server address and port

Python
import socket

Step 2: Create the socket object

Python
# AF_INET = IPv4 address family
# SOCK_STREAM = TCP protocol
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Step 3: Connect and send data

Data sent over sockets must be in bytes, not strings. Use the b"" prefix for byte literals or call .encode() on a string. This is important to keep in mind when building any network tool. To run a server process in the background, see running terminal commands with Python.

Python
# Connect to the server
client.connect((target_host, target_port))

Step 4: Receive the response and close

Python
# Receive the response (up to 4096 bytes)
response = client.recv(4096)

TCP vs UDP: quick comparison

FeatureTCPUDP
ConnectionRequired (handshake)Connectionless
ReliabilityGuaranteed delivery and orderNo guarantees
SpeedSlower (overhead)Faster
Use casesHTTP, FTP, SSH, databasesVideo streaming, DNS, games

Frequently asked questions

What does recv(4096) mean?

It means “receive up to 4096 bytes in one call.” This is the buffer size. For small messages it is usually enough; for large data transfers you need a loop that calls recv() repeatedly until all data arrives.

Should I always call client.close()?

Yes. Not closing the socket leaks file descriptors. Use a try/finally block or a context manager (with socket.socket(...) as client:) to guarantee cleanup even if an error occurs.

Can the socket module handle HTTPS?

Use ssl.wrap_socket() or Python’s ssl module to add TLS to a raw socket. For typical HTTP/HTTPS requests, the requests library is far more convenient.

Understanding socket-level TCP communication gives you the foundation to build custom network tools, proxies, and monitoring systems. Once comfortable with this, explore Python’s asyncio for handling multiple simultaneous connections efficiently.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    TOML configuration in a Python project
    Best Practices
    Foto de perfil de Leandro Hirt da Academify

    Python tomllib: Read TOML Files

    Learn how to read TOML with Python tomllib, validate settings, handle parse errors, and organize projects with pyproject.toml.

    Ler mais

    Tempo de leitura: 6 minutos
    24/07/2026
    Developer monitoring structured Python application logs
    Best Practices
    Foto de perfil de Leandro Hirt da Academify

    Observability in Python with structlog

    Build practical Python observability with structlog, JSON events, request context, tests, performance controls, and deployment guidance.

    Ler mais

    Tempo de leitura: 5 minutos
    24/07/2026
    Secure Python application configuration with Pydantic Settings
    Best Practices
    Foto de perfil de Leandro Hirt da Academify

    Pydantic Settings for Safe Config

    Learn how to validate environment variables, manage secrets, and organize Python application settings with Pydantic Settings.

    Ler mais

    Tempo de leitura: 5 minutos
    23/07/2026
    Desenvolvedor programando em Python com Ruff para lint e formatação
    Best Practices
    Foto de perfil de Leandro Hirt da Academify

    Ruff: Lint and Format Python Code

    Learn Ruff for Python linting, formatting, automatic fixes, pyproject.toml, VS Code and CI with a practical project configuration.

    Ler mais

    Tempo de leitura: 9 minutos
    22/07/2026
    2 balões de comentários em um fundo laranja
    Best Practices
    Foto de perfil de Leandro Hirt da Academify

    Python Comments: Syntax and Best Practices

    Learn Python comments with single-line and inline examples, block explanations, TODO notes, docstrings, security and performance context, review standards, and

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    Pessoa programando em um notebook, vista de trás, com código desfocado exibido na tela em um fundo escuro
    Best Practices
    Foto de perfil de Leandro Hirt da Academify

    Python Docstrings: Functions, Classes, and Modules

    Learn Python docstrings for functions, classes, methods, modules, parameters, returns, exceptions, examples, pydoc, conventions, and documentation tools.

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026