Master Python Socket Programming: From Basics to Full TCP/UDP Client‑Server

This guide introduces Python’s socket module, explains socket families and types, details essential server and client functions, walks through step‑by‑step TCP connection creation, and provides complete server and client code examples for practical network programming.

ITPUB
ITPUB
ITPUB
Master Python Socket Programming: From Basics to Full TCP/UDP Client‑Server

Introduction

Socket is a communication endpoint that can connect processes on the same host or across different hosts and networks. Python’s socket module provides classes and methods that simplify socket programming, and this note records the essential concepts and usage.

Socket families and types

socket.AF_UNIX

– local inter‑process communication on Unix systems. socket.AF_INET – IPv4 network communication. socket.AF_INET6 – IPv6 network communication. socket.SOCK_STREAM – stream‑oriented socket (TCP). socket.SOCK_DGRAM – datagram socket (UDP). socket.SOCK_RAW – raw socket for low‑level protocols such as ICMP. socket.SOCK_SEQPACKET – reliable sequenced packet service.

Key socket functions

Server side

socket.bind(address)

– bind the socket to a (host, port) tuple. socket.listen(backlog) – start listening for incoming TCP connections; backlog is the maximum pending connections (minimum 1). socket.accept() – accept a pending connection and return a new socket object and the client address. socket.recv(bufsize[, flags]) – receive up to bufsize bytes from a TCP socket. socket.send(data[, flags]) – send a byte string over a TCP socket. socket.sendall(data[, flags]) – ensure the entire byte string is transmitted. socket.close() – close the socket.

Client side

socket.connect(address)

– connect to a remote (host, port) tuple; raises socket.error on failure. socket.connect_ex(address) – like connect but returns 0 on success or an error number.

Same send, recv, and close methods as the server.

Creating a TCP connection

Server steps

Create a socket: tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) Bind to an address and port: tcpSock.bind((host, port)) Listen for connections: tcpSock.listen(backlog) Accept a client: conn, addr = tcpSock.accept() Exchange data using conn.send() and conn.recv().

Close the connection with conn.close() and finally tcpSock.close().

Client steps

Create a socket with the same parameters.

Connect to the server: tcpCliSock.connect((host, port)) Send data using tcpCliSock.send() and receive responses with tcpCliSock.recv().

Terminate the session with tcpCliSock.close().

Sample implementation

Server (server.py):

#coding:utf8
import socket
from time import ctime

HOST = ''
PORT = 9999
BUFSIZE = 1024
ADDR = (HOST, PORT)

tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSock.bind(ADDR)
tcpSock.listen(5)

while True:
    print('waiting for connection ....')
    tcpCliSock, addr = tcpSock.accept()
    print('...connected from ', addr)
    while True:
        data = tcpCliSock.recv(BUFSIZE)
        if not data:
            break
        elif data == 'exit':
            tcpCliSock.send('see you again')
            tcpCliSock.close()
            exit(0)
        tcpCliSock.send('%s, %s ' % (ctime(), data))
        print('[%s]:' % ctime(), data)
    tcpCliSock.close()

tcpSock.close()

Client (client.py):

#coding:utf8
import socket

HOST = '10.0.2.6'  # server IP
PORT = 9999
BUFSIZE = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    try:
        data = raw_input('> ')
        if not data:
            break
        tcpCliSock.send(data)
        resp = tcpCliSock.recv(BUFSIZE)
        if not resp:
            break
        print('%s say: %s' % (HOST, resp))
        if resp == 'see you again':
            exit(0)
    except (KeyboardInterrupt, SystemExit):
        tcpCliSock.close()
        exit(0)

The two scripts demonstrate a minimal TCP client‑server exchange, including connection setup, message exchange, and graceful shutdown.

Socket connection diagram
Socket connection diagram
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

TCPNetwork programmingSocketUDPclient-server
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.