Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python Socket Programming Tutorial – Complete Guide with Examples

Python - Socket Programming

Socket programming is the foundation of network communication in Python. It allows two devices (or programs) to communicate with each other over a network using protocols like TCP or UDP.

With socket programming, you can build:

  • Chat applications
  • Web servers
  • File transfer tools
  • Multiplayer games
  • Network-based services

In this tutorial, you will learn socket programming in Python with clear examples and real-world understanding.


What is Socket Programming?

Socket programming is:

A method of enabling communication between two machines using sockets as endpoints.

A socket acts like a communication channel between a client and a server.


What is a Socket?

A socket is:

An endpoint that sends and receives data over a network.

Each socket has:

  • IP address
  • Port number

Types of Sockets

1. Stream Socket (TCP)

  • Reliable communication
  • Connection-based
  • Ensures data delivery

2. Datagram Socket (UDP)

  • Fast communication
  • Connectionless
  • No guarantee of delivery

Python Socket Module

Python provides socket programming using:

import socket

TCP Socket Programming (Client-Server Model)

Server Side

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind(("localhost", 9090))
server.listen(1)

print("Server is waiting...")

conn, addr = server.accept()
print("Connected with", addr)

data = conn.recv(1024).decode()
print("Client:", data)

conn.send("Hello from server".encode())

conn.close()
server.close()

Client Side

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client.connect(("localhost", 9090))

client.send("Hello Server".encode())

response = client.recv(1024).decode()
print("Server:", response)

client.close()

How TCP Socket Works

  1. Server creates socket
  2. Server listens for connections
  3. Client connects to server
  4. Data is exchanged
  5. Connection is closed

Output Example

Server Output

Server is waiting...
Connected with ('127.0.0.1', 51234)
Client: Hello Server

Client Output

Server: Hello from server

UDP Socket Programming

UDP is faster but less reliable.


UDP Server

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

server.bind(("localhost", 9091))

print("UDP Server running")

data, addr = server.recvfrom(1024)
print("Received:", data.decode())

server.sendto("Hello UDP Client".encode(), addr)

UDP Client

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

client.sendto("Hello UDP Server".encode(), ("localhost", 9091))

data, addr = client.recvfrom(1024)
print("Server:", data.decode())

client.close()

Difference Between TCP and UDP

FeatureTCPUDP
ConnectionRequiredNot required
ReliabilityHighLow
SpeedSlowerFaster
Use CaseWeb, EmailGaming, Streaming

Important Socket Methods

Server Methods

  • bind() → Assign IP and port
  • listen() → Wait for clients
  • accept() → Accept connection

Client Methods

  • connect() → Connect to server
  • send() → Send data
  • recv() → Receive data

Real-World Applications

Socket programming is used in:

  • Web servers (HTTP/HTTPS)
  • Chat applications
  • Online games
  • File transfer systems
  • Streaming services
  • IoT devices

Example: Simple Chat System Idea

# Server handles multiple clients and broadcasts messages

Advantages of Socket Programming

  • Real-time communication
  • Cross-platform networking
  • Flexible architecture
  • Supports distributed systems

Challenges

  • Network latency
  • Security risks
  • Data loss in UDP
  • Connection handling complexity

Best Practices

1. Always close sockets

socket.close()

2. Handle exceptions properly

try:
    pass
except Exception as e:
    print(e)

3. Use proper buffer size

recv(1024)

4. Avoid blocking calls without timeout


Common Mistakes

1. Not closing connections


2. Hardcoding ports without checking availability


3. Not handling disconnected clients


Summary

Socket programming in Python enables communication between devices using TCP and UDP protocols. It forms the backbone of network applications such as chat systems, web servers, and real-time services.

Key Takeaways

  • Socket is the core of network communication
  • TCP is reliable, UDP is faster
  • Client-server model is widely used
  • Python socket module simplifies networking
  • Essential for real-world applications

Mastering socket programming is a major step toward building powerful network-based Python applications.




Post a Comment

0 Comments