DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

Connect to a TCP Server with a Simple Python Client

A minimal Python TCP client connects to a listening server, sends bytes, and reads a response. Learn the difference between opening a connection and defining the application protocol.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s built-in socket module to connect to a server, send bytes, and receive bytes. The server must already be listening on the host and port you specify. A successful TCP connection establishes a reliable byte stream; it does not define what the application should send or how to tell when a reply is complete.

A minimal TCP client

This blocking example uses socket.create_connection(), sends a byte string, then reads up to 1,024 bytes:

As an Amazon Associate I earn from qualifying purchases.

import socket

HOST = "example.com"
PORT = 50007

with socket.create_connection((HOST, PORT), timeout=5) as sock:
    sock.sendall(b"Hello")
    response = sock.recv(1024)
    print(response)

Replace the example host, port, and message with values for a server that is running and expects those bytes. The example prints the reply as bytes, such as b'Hello'; decode it only if the server’s protocol specifies a text encoding.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The with block closes the socket when the block ends, including if an error occurs. The timeout applies to socket operations; it does not guarantee every operating system will report a connection timeout on the same schedule.

Connection setup is separate from the protocol

TCP provides a connected stream of bytes, not application-level message boundaries. sendall() sends the supplied bytes, while recv(1024) returns up to 1,024 bytes currently available. It may return fewer, and one call is not a general guarantee that a whole response has arrived.

To build a complete exchange, follow the server’s protocol: it must specify the message format, how the receiver detects the end of a message (for example, a length field or delimiter), and what response to expect. The short send-and-receive pattern is suitable only when the peer’s protocol makes that exchange clear.

Choose how to create the connection

Approach Example When it fits
Convenience function socket.create_connection((HOST, PORT), timeout=5) Simplifies connecting to a host and port. For a hostname, Python tries available IPv4 and IPv6 addresses in turn until one connects.
Explicit socket socket.socket(socket.AF_INET, socket.SOCK_STREAM) followed by connect((HOST, PORT)) Makes the socket’s address family and stream type explicit. This form is useful when you want to show or control socket construction directly.

Here is the explicit IPv4 form:

import socket

HOST = "example.com"
PORT = 50007

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.settimeout(5)
    sock.connect((HOST, PORT))
    sock.sendall(b"Hello")
    response = sock.recv(1024)
    print(response)

The two approaches are API choices, not a performance ranking. The explicit example requests IPv4 with AF_INET; create_connection() can try both IPv4 and IPv6 for hostnames.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Client versus server socket

A client initiates a connection with connect(). It does not use the server’s listening sequence of bind(), listen(), and accept(). A server listens at its destination host and port, accepts an incoming connection, and exchanges data using the accepted socket; the client connects and exchanges data using its own socket.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When a connection fails

  • Connection refused: Check that the host and port are correct and that a server is listening and reachable there.
  • Timeout: Check the destination and network availability. Python’s socket timeout is useful for limiting waits, but the operating system’s network stack can also determine timeout behavior.
  • Hostname or address-family issue: With create_connection(), Python resolves a non-numeric hostname and tries available IPv4 and IPv6 addresses. If you construct an AF_INET socket yourself, you have explicitly chosen IPv4.

Connection failures are reported as exceptions by the socket APIs. Consult Python’s socket module documentation for API details, and the Socket Programming HOWTO for an introduction to blocking sockets and client-server communication.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.