Introduction to Sockets
Sockets are fundamental for network communication in Python. They allow programs to interact with other devices over a network using protocols like TCP or UDP. 📡
- TCP (Transmission Control Protocol): Reliable, connection-oriented communication
- UDP (User Datagram Protocol): Faster but less reliable, connectionless communication
Basic Socket Operations
Here’s how to create a simple socket in Python:
- Import socket module:
import socket
- Create a socket object:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- Bind the socket to an address:
s.bind(("localhost", 12345))
- Listen for incoming connections:
s.listen(1)
- Accept connections and send/receive data:
conn, addr = s.accept() conn.send("Hello from server!".encode()) data = conn.recv(1024).decode()
Example: Echo Server
A simple echo server that sends back received data:
import socket
# Create socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(1)
print("Server is listening...")
conn, addr = server_socket.accept()
print(f"Connected to {addr}")
data = conn.recv(1024).decode()
conn.send(data.encode())
conn.close()
Applications of Sockets
Sockets are used in:
- Web servers (HTTP)
- Chat applications (TCP)
- Gaming (UDP)
- File transfer (TCP)
Explore more about network programming in Python: /en/courses/Python_Tutorials/network_programming