Hello, young Python coder! Now that you know what a network is, it's time to make your computer talk to other computers. We will use Python to send and receive messages over a network. This is called socket programming.
Imagine you have a walkie-talkie. You can press a button and talk, and your friend on the other walkie-talkie can hear you. That's what a socket does for computers. It lets them send messages back and forth.
In this module, we will learn how to use Python's socket module to create programs that communicate over a network. We will build both a server (the one that listens) and a client (the one that connects). We will also learn about TCP and UDP, the two main ways to send data.
By the end of this module, you will be able to write Python programs that send and receive messages over the internet. You will be a true network programmer!
After reading this module, you will be able to:
socket module to create network connections.In a school called Codeville, two friends named Python and Netty wanted to send messages to each other across the school. They couldn't shout because the teachers would get angry.
Python said, "Let's build walkie-talkies! I will press a button, say something, and you will hear it." So they built small devices called sockets. Python's device was the client – it connected to Netty's device. Netty's device was the server – it listened for connections.
They had two ways to send messages: TCP was like a phone call – you dial, talk, and hang up, and you know the message arrived. UDP was like sending a letter – you drop it in a mailbox and hope it arrives, but you don't know for sure.
Soon, all the students in Codeville had their own sockets. They could send messages, share files, and even play games together. Python and Netty were heroes!
This is exactly how Python sockets work – they create a communication channel between programs.
Definition: A socket is an endpoint for communication between two computers. It's like a door that programs use to send and receive data.
Why it is important: Sockets are the foundation of network programming. They allow programs to communicate over the internet.
Simple explanation: Think of a socket as a door. One program knocks (connects), and another program opens the door (accepts).
Real-life example: When you use a web browser, it creates a socket to connect to a web server.
School example: Your school's chat application uses sockets to send messages between students.
Home example: When you play a multiplayer game, your computer uses sockets to talk to the game server.
Nigerian example: A Nigerian bank's mobile app uses sockets to communicate with the bank's servers.
+--------+ +----------+ +--------+
| Client |-----| Socket |-----| Server |
| | | (door) | | |
+--------+ +----------+ +--------+
Mini summary: A socket is a door that programs use to send and receive data.
Definition: TCP (Transmission Control Protocol) is connection-oriented and reliable. UDP (User Datagram Protocol) is connectionless and faster but less reliable.
Why it is important: Different applications need different types of communication.
Simple explanation: TCP is like a phone call – you know the person hears you. UDP is like a letter – you send it and hope it arrives.
Real-life example: Web browsing uses TCP (reliable). Video streaming often uses UDP (faster).
School example: An online test might use TCP to make sure answers are not lost.
Home example: A video call uses UDP for speed, even if some packets are lost.
Nigerian example: A Nigerian online payment system uses TCP for reliable transactions.
| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented | Connectionless |
| Reliability | High (guaranteed delivery) | Low (best-effort) |
| Speed | Slower | Faster |
| Examples | HTTP, HTTPS, FTP | DNS, VoIP, streaming |
Mini summary: TCP is reliable but slower; UDP is faster but less reliable.
Definition: Python's socket module provides a way to create and use sockets for network communication.
Why it is important: It is the standard way to do network programming in Python.
Simple explanation: It's like having a toolbox with all the tools you need to build network connections.
Real-life example: Many Python applications (web servers, chat apps) use the socket module.
School example: A Python program that sends messages between computers in the school lab.
Home example: A Python script that checks the weather by connecting to a weather server.
Nigerian example: A Nigerian developer uses the socket module to build a payment gateway.
import socket # import the socket toolbox
# Now you can use socket functions
Mini summary: The socket module is the toolbox for network programming in Python.
Definition: To create a socket, you use socket.socket(). You need to specify the address family and socket type.
Why it is important: This is the first step to using sockets.
Simple explanation: Like picking up a walkie-talkie and turning it on.
Real-life example: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) creates a TCP socket.
School example: You create a socket in your Python program to send data to the teacher's computer.
Home example: You create a socket to connect to a game server.
Nigerian example: A Nigerian developer creates a socket to connect to a bank's API.
import socket
# Create a TCP socket
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Create a UDP socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Mini summary: socket.socket() creates a new socket.
Definition: A TCP server uses bind() to attach to a port and listen() to wait for connections.
Why it is important: This is how a server becomes available for clients to connect.
Simple explanation: Like putting up a sign that says "Open for business" on a store.
Real-life example: A web server binds to port 80 and listens for incoming HTTP requests.
School example: The school's chat server binds to a port so students can connect.
Home example: A server on your home network binds to a port for local apps.
Nigerian example: A Nigerian company's server binds to a port for customer connections.
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345)) # Bind to port 12345
server_socket.listen(5) # Listen for connections
print("Server is listening...")
Mini summary: bind() and listen() make a server ready for clients.
Definition: The accept() method waits for a client to connect and returns a new socket for that client.
Why it is important: This is how a server talks to an individual client.
Simple explanation: Like a receptionist who greets each customer and assigns them to a room.
Real-life example: A web server accepts a connection from your browser.
School example: The chat server accepts connections from each student.
Home example: A file server accepts a connection from your laptop.
Nigerian example: A bank's server accepts connections from mobile banking apps.
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(5)
client_socket, address = server_socket.accept()
print("Connected to:", address)
Mini summary: accept() waits for and accepts a client connection.
Definition: A TCP client uses connect() to connect to a server.
Why it is important: This is how a client starts communicating with a server.
Simple explanation: Like dialing a phone number to call someone.
Real-life example: Your web browser connects to a web server.
School example: Your Python program connects to the school's chat server.
Home example: Your game client connects to the game server.
Nigerian example: A banking app connects to the bank's server.
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 12345))
print("Connected to server!")
Mini summary: connect() connects a client to a server.
Definition: send() sends data, and recv() receives data.
Why it is important: This is how programs actually communicate.
Simple explanation: Like talking into a walkie-talkie (send) and listening (recv).
Real-life example: A web browser sends an HTTP request and receives a web page.
School example: Students send messages to the chat server and receive replies.
Home example: Your game sends player actions and receives game updates.
Nigerian example: A mobile app sends a payment request and receives a confirmation.
# Server side
data = client_socket.recv(1024) # Receive up to 1024 bytes
print("Received:", data.decode())
client_socket.send("Hello, client!".encode()) # Send a reply
# Client side
client_socket.send("Hello, server!".encode()) # Send a message
response = client_socket.recv(1024) # Receive reply
print("Server says:", response.decode())
Mini summary: send() sends data; recv() receives data.
Definition: close() closes a socket and ends the connection.
Why it is important: It frees up resources and tells the other side that communication is done.
Simple explanation: Like hanging up the phone.
Real-life example: A web server closes the connection after sending a web page.
School example: Students close their sockets when they log out of the chat.
Home example: Your game client closes the socket when you quit the game.
Nigerian example: A banking app closes the socket after a transaction.
client_socket.close() # Close the connection
server_socket.close() # Close the server socket
Mini summary: close() ends a socket connection.
Definition: UDP sockets use sendto() and recvfrom() without establishing a connection.
Why it is important: UDP is faster and useful for streaming and broadcasts.
Simple explanation: Like sending a letter without knowing if the person is home.
Real-life example: DNS queries use UDP.
School example: Broadcasting a message to all students in a school network.
Home example: Streaming music uses UDP for speed.
Nigerian example: A Nigerian company might use UDP for real-time data feeds.
import socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Send to a server
udp_socket.sendto("Hello".encode(), ('localhost', 12345))
# Receive from a client
data, address = udp_socket.recvfrom(1024)
print("Received from:", address, "Data:", data.decode())
Mini summary: UDP sockets use sendto() and recvfrom().
Definition: A complete TCP server that listens, accepts, and echoes back messages.
Why it is important: Shows all the steps together.
Simple explanation: Like a parrot that repeats everything you say.
Real-life example: An echo server is used for testing network connections.
School example: Students can test their network programs with an echo server.
Home example: You can run an echo server to test your socket code.
Nigerian example: A developer might use an echo server to test network connectivity.
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 12345))
server.listen(5)
print("Echo server running on port 12345")
while True:
client, addr = server.accept()
print("Connected to:", addr)
data = client.recv(1024)
if data:
client.send(data) # Echo back the data
client.close()
Mini summary: A complete TCP server listens, accepts, and echoes data back.
Definition: A complete TCP client that connects to the echo server and sends messages.
Why it is important: Shows how a client interacts with a server.
Simple explanation: Like talking to the parrot and hearing it repeat.
Real-life example: A web browser connecting to a web server.
School example: Students can send messages to the echo server.
Home example: You can test your echo server with this client.
Nigerian example: A client program that tests a remote server.
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 12345))
client.send("Hello, server!".encode())
response = client.recv(1024)
print("Server replied:", response.decode())
client.close()
Mini summary: A complete TCP client connects, sends, and receives.
Definition: A server can handle multiple clients using threads or selectors.
Why it is important: Real servers serve many clients at once.
Simple explanation: Like a restaurant that can serve many customers.
Real-life example: A web server handles thousands of requests per second.
School example: A chat server handles many students simultaneously.
Home example: A game server handles multiple players.
Nigerian example: A bank's server handles many customer requests at once.
import socket
import threading
def handle_client(client_socket):
data = client_socket.recv(1024)
client_socket.send(data) # Echo back
client_socket.close()
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 12345))
server.listen(5)
while True:
client, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(client,))
thread.start()
Mini summary: Threads help servers handle multiple clients.
Definition: Errors can happen in network programming. We use try/except to handle them.
Why it is important: Prevents programs from crashing.
Simple explanation: Like having a backup plan if something goes wrong.
Real-life example: A web browser handles connection errors gracefully.
School example: A chat client shows an error message if the server is down.
Home example: A game shows "connection lost" instead of crashing.
Nigerian example: A banking app shows "unable to connect" if the network is down.
import socket
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 12345))
client.send("Hello".encode())
response = client.recv(1024)
print(response)
except ConnectionRefusedError:
print("Server is not responding. Is it running?")
except Exception as e:
print("An error occurred:", e)
finally:
client.close()
Mini summary: Error handling prevents crashes and gives useful messages.
Definition: A timeout is a time limit for waiting for a response.
Why it is important: Prevents programs from waiting forever.
Simple explanation: Like waiting for a bus for only 10 minutes before walking.
Real-life example: A web browser waits only a few seconds before showing an error.
School example: A chat app waits for a reply for 5 seconds.
Home example: A game client waits for the server to respond.
Nigerian example: A mobile app uses timeouts to handle slow networks.
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.settimeout(5) # Wait only 5 seconds
try:
client.connect(('localhost', 12345))
data = client.recv(1024)
except socket.timeout:
print("Connection timed out.")
Mini summary: Timeouts prevent programs from waiting forever.
Teachers, this module is hands-on. Encourage students to run the examples. Start with the echo server and client – it's a great way to see sockets in action. Use the walkie-talkie analogy to explain sockets. Emphasize the difference between TCP and UDP. Allow students to experiment with different ports and messages.
Parents, help your child run the Python examples on their computer. If possible, set up a simple client-server on two computers. Show them how programs communicate. This module is the core of network programming – encourage experimentation and curiosity.
socket module is part of Python's standard library – no installation needed.socket.socket() creates a socket.bind() and listen() are for servers.connect() is for clients.send() and recv() are for data exchange.close() ends the connection.sendto() and recvfrom().AF_INET for IPv4.try/except) in socket programs.threading or selectors for multiple clients.
+--------+ +---------+ +--------+
| Client |---->| Socket |---->| Server |
| | | (door) | | |
+--------+ +---------+ +--------+
| |
| send() |
| ---------------------------->|
| |
| recv() |
| <----------------------------|
| |
Client Server
| |
| SYN (connect) |
| ------------------------>|
| |
| SYN-ACK (acknowledge) |
| <------------------------|
| |
| ACK (connected) |
| ------------------------>|
| |
| Data transfer begins |
Server:
socket() ---> bind() ---> listen() ---> accept() ---> send/recv() ---> close()
Client:
socket() ---> connect() ---> send/recv() ---> close()
| Feature | TCP | UDP |
|---|---|---|
| Reliability | Guaranteed delivery | Best-effort |
| Ordering | Guaranteed order | No guarantee |
| Connection | Connection-oriented | Connectionless |
| Speed | Slower | Faster |
| Use Cases | HTTP, FTP, SMTP | DNS, VoIP, streaming |
| Function | Server | Client |
|---|---|---|
| socket() | Yes | Yes |
| bind() | Yes | No |
| listen() | Yes | No |
| accept() | Yes | No |
| connect() | No | Yes |
| send() | Yes | Yes |
| recv() | Yes | Yes |
| close() | Yes | Yes |
Fantastic work! You have completed Module 2: Python Sockets – Writing Network Programs.
You learned about sockets – the endpoints for network communication. You discovered the difference between TCP (reliable) and UDP (fast). You used Python's socket module to create TCP and UDP servers and clients.
You learned the key functions: socket(), bind(), listen(), accept(), connect(), send(), recv(), and close(). You also learned how to handle multiple clients, error handling, and timeouts.
You now have the skills to write network programs in Python. In Module 3, we will learn about HTTP and working with APIs – how to interact with web services and build web applications.
bind() do? It attaches a socket to a port.listen() do? It waits for connections.accept() do? It accepts an incoming connection.connect() do? It connects to a server.send() for TCP and sendto() for UDP.recv() for TCP and recvfrom() for UDP.bind() do?listen() do?accept() do?connect() do?send() and sendto()?bind() is used on the client side. (False)listen() is used on the server side. (True)accept() accepts a client connection. (True)connect() is used by clients. (True)send() is used for UDP. (False – it's for TCP)recvfrom() is used for UDP. (True)bind() is used by:
listen() is used by:
accept() returns:
connect() is used by:
send() is used for:
sendto() is used for:
recv() is used for:
recvfrom() is used for:
close() is used to:
Match the term on the left with the correct definition on the right.
| Term | Definition |
|---|---|
| 1. bind() | A. Connect to a server |
| 2. listen() | B. Attach to a port |
| 3. accept() | C. Wait for connections |
| 4. connect() | D. Accept a client |
| 5. send() | E. Send data |
Answers: 1-B, 2-C, 3-D, 4-A, 5-E
Scenario 1: You are building a chat application. Should you use TCP or UDP? Why?
Scenario 2: Your Python program needs to connect to a server, but the server is not running. What error might occur and how would you handle it?
Scenario 3: You want to build a server that can handle many clients at once. What technique would you use and why?
Build a Chat System: In groups of 3-4, build a simple chat system using TCP sockets. One person runs the server, and others run clients. Send messages between clients through the server. Add features like sending to all clients (broadcast).
Create an Echo Client-Server: Write a TCP echo server and client. The client sends a message, and the server echoes it back. Run both programs on your computer and test them.
Build a Simple File Transfer Program: Create a TCP server and client where the client can send a file to the server, and the server saves it. Use the send() and recv() functions to transfer the file in chunks.
Test Your Echo Server: Write a TCP echo server and client. Test sending different types of data – strings, numbers, and even a simple JSON object. Observe how the data is received and echoed.
Build a Multi-Client Chat Server: Build a TCP chat server that can handle multiple clients. Each client can send a message, and the server broadcasts it to all other clients. Use threads to handle each client.
Fill-in-the-Blank Answers:
True or False Answers: 1-F, 2-F, 3-F, 4-T, 5-T, 6-T, 7-F, 8-T, 9-F, 10-T
Multiple Choice Answers: 1-B, 2-B, 3-C, 4-B, 5-B, 6-A, 7-A, 8-A, 9-B, 10-A, 11-B, 12-B, 13-B, 14-A, 15-A
bind(), listen(), and accept().connect().send() and recv() are for TCP.sendto() and recvfrom() are for UDP.In Module 3, we will explore HTTP and Working with APIs. You will learn how to use Python to make web requests, work with REST APIs, and build web applications. This is a practical step that will let you interact with real web services.
To prepare, think about these questions:
You are now ready for Module 3. Keep coding and exploring!
🎉 Congratulations! You have completed Module 2: Python Sockets – Writing Network Programs. See you in Module 3!