0
0
PythonHow-ToBeginner · 4 min read

How to Create TCP Client in Python: Simple Guide

To create a TCP client in Python, use the socket module to create a socket object, then connect it to a server using connect(). After connecting, you can send and receive data with send() and recv() methods.
📐

Syntax

Here is the basic syntax to create a TCP client in Python:

  • socket.socket(socket.AF_INET, socket.SOCK_STREAM): Creates a TCP socket.
  • connect((host, port)): Connects the socket to the server at the given host and port.
  • send(data): Sends data to the server.
  • recv(buffer_size): Receives data from the server.
  • close(): Closes the socket connection.
python
import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('server_ip_or_hostname', 12345))
client_socket.send(b'Hello Server')
data = client_socket.recv(1024)
client_socket.close()
💻

Example

This example shows a TCP client connecting to a server on localhost at port 65432, sending a message, and printing the response.

python
import socket

HOST = '127.0.0.1'  # Server IP address (localhost)
PORT = 65432        # Server port

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, server')
    data = s.recv(1024)

print('Received', repr(data))
Output
Received b'Hello, client'
⚠️

Common Pitfalls

Common mistakes when creating a TCP client include:

  • Not using socket.AF_INET and socket.SOCK_STREAM for TCP sockets.
  • Forgetting to call connect() before sending data.
  • Not handling exceptions for connection errors.
  • Not closing the socket after use, which can cause resource leaks.

Always use with statement or explicitly call close() to free resources.

python
import socket

# Wrong: Missing connect call
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    client_socket.send(b'Hello')  # This will raise an error
except Exception as e:
    print('Error:', e)
finally:
    client_socket.close()

# Right: Proper connect and close
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
    client_socket.connect(('127.0.0.1', 65432))
    client_socket.send(b'Hello')
Output
Error: [Errno 107] Transport endpoint is not connected
📊

Quick Reference

Remember these key points when creating a TCP client in Python:

  • Use socket.socket(socket.AF_INET, socket.SOCK_STREAM) for TCP.
  • Always call connect() before sending data.
  • Use send() or sendall() to send bytes.
  • Use recv() to receive bytes.
  • Close the socket with close() or use with for automatic closing.

Key Takeaways

Use socket.socket with AF_INET and SOCK_STREAM to create a TCP client socket.
Always call connect() before sending or receiving data.
Send and receive data as bytes using send()/sendall() and recv().
Close the socket after use to free system resources.
Handle exceptions to manage connection errors gracefully.