Master Python Socket Programming: Build a Full‑Duplex TCP Chat App

This article introduces Python's socket module, explains core concepts such as IP, ports, and protocols, demonstrates essential socket functions, and provides complete client‑server code for a simple full‑duplex TCP chat application, enabling readers to quickly start network programming in Python.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Socket Programming: Build a Full‑Duplex TCP Chat App

Introduction

Socket, also known as a socket, is the foundation of all network communication. Network communication is essentially inter‑process communication, identified by IP address, protocol, and port number (0‑65535, typically >1024 for user ports). Common protocols include TCP, UDP, and IP.

1. Import Socket Module

import socket

2. Basic Socket Usage

1. Create a Simple Socket Connection

# Create TCP/IP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Stream socket
# Create UDP/IP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # Datagram socket
socket.AF_UNIX      # Unix domain socket (local IPC only)
socket.AF_INET6    # IPv6 communication
socket.SOCK_RAW    # Raw socket for ICMP, ARP, etc.
socket.SOCK_SEQPACKET  # Reliable sequenced packet service

2. Protocol to Port Mapping

Application    FTP  TFTP  TELNET  SMTP  DNS   HTTP  SSH   MYSQL  POP3   MONGO
Port           21,20 69   23     25    53    80    22    3306   110   27017
Protocol       TCP   UDP  TCP    TCP   UDP   TCP   TCP    TCP   TCP    TCP

3. Socket Functions

# Create a socket connection (higher level than connect, resolves host names, supports IPv4/IPv6)
socket.create_connection(address=('localhost', 4320), timeout=4, source_address=('localhost', 4320))
# Create a pair of connected sockets (non‑inheritable)
socket.socketpair(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0)
# Get a socket from a file descriptor
socket.fromfd(fd=ab.fileno(), family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0)
# Socket type
socket.SocketType
# Get address info (supports IPv4/IPv6)
socket.getaddrinfo(host='localhost', port=3453, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP, flags=0)
# Host name utilities
socket.gethostname()
socket.getfqdn()
socket.getfqdn(socket.gethostname())
# Resolve host name to IP (IPv4 only)
socket.gethostbyname('www.baidu.com')
socket.gethostbyname_ex('www.baidu.com')
# Reverse lookup (IPv4/IPv6)
socket.gethostbyaddr('192.168.1.4')
# Resolve address info
socket.getnameinfo(('192.168.1.4', 5434), 0)
# IPv6 support check
socket.has_ipv6
# Service name to port
socket.getservbyname('https', 'tcp')
# Port to service name
socket.getservbyport(443, 'tcp')
# Unix‑only hostname set
socket.sethostname(name)
# Unix‑only network interface list
socket.if_nameindex()
# IPv4 address serialization
socket.inet_aton('127.0.0.1')
# IPv4 address deserialization
socket.inet_ntoa(b'\x7f\x00\x00\x01')

4. Socket Functions

1) Server‑side Functions

s.bind((host, port))          # Bind address to socket as (host, port) tuple
s.listen(num)                # Listen for up to num connections
s.accept()                   # Accept a client connection, returns (conn, (host, port))

2) Client‑side Functions

s.connect((host, port))      # Connect to server at (host, port)
s.connect_ex((host, port))   # Like connect but returns error code instead of raising

3) General Functions

s.recv(size, flag)            # Receive up to size bytes, returns data as string
s.send(data, flag)           # Send data, returns number of bytes sent (may be partial)
s.sendall(data, flag)        # Send all data, returns None on success
s.recvfrom(bufsize, flag)    # Like recv but also returns sender address tuple
s.sendto(data, flag, addr)   # Send data to specific address (used for UDP)
s.getpeername()              # Return remote address of the socket
s.getsockname()              # Return local address of the socket
s.setsockopt(level, optname, value)  # Set socket option
s.getsockopt(level, optname, buflen) # Get socket option value
s.settimeout(seconds)        # Set timeout for socket operations
s.gettimeout()               # Get current timeout (None if not set)
s.close()                    # Close the socket
s.fileno()                   # File descriptor of the socket
s.shutdown(how)              # Shut down one or both halves of the connection
s.setblocking(bool)         # Enable/disable blocking mode
s.makefile()                 # Create a file‑like object associated with the socket

5. Simple Client‑Server Interaction

Server.py

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Create socket object
s.bind(('127.0.0.1', 4323))                         # Bind address
s.listen(5)                                         # Listen for up to 5 connections
while True:
    conn, addr = s.accept()                         # Wait for client connection
    print('欢迎{}'.format(addr))                     # Print client info
    while True:
        data = conn.recv(1024)
        dt = data.decode('utf-8')
        print('收到:', dt)
        aa = input('服务器发出:')
        if aa == 'quit':
            conn.close()
            s.close()
            break
        else:
            conn.send(aa.encode('utf-8'))
Server output illustration
Server output illustration

Client.py

import socket
import sys
c = socket.socket()                                 # Create socket object
c.connect(('127.0.0.1', 4323))                      # Establish connection
while True:
    ab = input('客户端发出:')
    if ab == 'quit':
        c.close()
        sys.exit(0)
    else:
        c.send(ab.encode('utf-8'))
        data = c.recv(1024)
        print('收到:', data.decode('utf-8'))
Client output illustration
Client output illustration

Conclusion

Python socket programming is not difficult, but writing robust sockets requires understanding many APIs; this article showcases most commonly used functions to help readers get started quickly.

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
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

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.