0
0
PythonHow-ToBeginner · 3 min read

How to Create a TCP Server in Python: Simple Guide

To create a TCP server in Python, use the socket module to create a socket, bind it to an IP address and port, then listen for incoming connections with listen(). Accept connections using accept() and handle client communication with recv() and send().
📐

Syntax

Here is the basic syntax to create a TCP server using Python's socket module:

  • socket.socket(socket.AF_INET, socket.SOCK_STREAM): Creates a TCP socket.
  • bind((host, port)): Binds the socket to a network address and port.
  • listen(backlog): Starts listening for incoming connections.
  • accept(): Accepts a connection and returns a new socket and client address.
  • recv(buffer_size): Receives data from the client.
  • send(data): Sends data to the client.
  • close(): Closes the socket.
python
import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(1)

client_socket, client_address = server_socket.accept()
data = client_socket.recv(1024)
client_socket.send(b'Hello Client')
client_socket.close()
server_socket.close()
💻

Example

This example creates a simple TCP server that waits for a client to connect, receives a message, and replies with a greeting.

python
import socket

HOST = '127.0.0.1'  # Localhost
PORT = 65432        # Non-privileged port

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print(f'Server listening on {HOST}:{PORT}')
    conn, addr = s.accept()
    with conn:
        print(f'Connected by {addr}')
        while True:
            data = conn.recv(1024)
            if not data:
                break
            print(f'Received: {data.decode()}')
            conn.sendall(b'Hello, client')
Output
Server listening on 127.0.0.1:65432 Connected by ('127.0.0.1', 54321) Received: Hello Server
⚠️

Common Pitfalls

Common mistakes when creating a TCP server in Python include:

  • Not calling listen() before accept(), which causes errors.
  • Forgetting to bind the socket to an address and port before listening.
  • Not handling client disconnections properly, leading to infinite loops or crashes.
  • Using blocking calls without timeout, which can freeze the server.
  • Not closing sockets after use, causing resource leaks.
python
import socket

# Wrong: Missing listen() call
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
# server_socket.listen(1)  # This line is missing
# client_socket, addr = server_socket.accept()  # This will raise an error

# Correct way
server_socket.listen(1)
client_socket, addr = server_socket.accept()
📊

Quick Reference

Summary tips for creating a TCP server in Python:

  • Always create the socket with socket.AF_INET and socket.SOCK_STREAM for TCP.
  • Bind to a valid IP address and port before listening.
  • Call listen() before accept().
  • Use recv() and send() to communicate with clients.
  • Close sockets properly to free resources.

Key Takeaways

Use Python's socket module with AF_INET and SOCK_STREAM to create a TCP server socket.
Bind the socket to an IP and port, then call listen() before accepting connections.
Handle client connections with accept(), then use recv() and send() to communicate.
Always close client and server sockets to avoid resource leaks.
Avoid missing listen() or bind() calls to prevent runtime errors.