Network Programming
Network Programming
UNIVERSITY COLLEGE.
SCHOOL OF TECHNOLOGY
NETWORK PROGRAMMING
SECOND SEMESTER
LEVEL 400
BY
MR ANDRENE ADDY
INTRODUCTION TO NETWORK
PROGRAMMING
Network programming involves writing software that enables computers to
communicate over a network.
It is widely used in applications such as web browsers, email clients, chat
applications, and cloud computing.
Key Concepts:
Client-Server Model: A communication framework where a client requests
services, and a server provides them.
Protocols: Rules that govern data transmission, including TCP, UDP, HTTP, FTP,
etc.
Sockets: Programming interfaces for network communication.
NETWORKING PROTOCOLS
Transmission Control Protocol (TCP)
Connection-oriented protocol.
Ensures reliable data transmission with error checking and retransmission.
Used in applications requiring guaranteed delivery (e.g., web browsing, email).
User Datagram Protocol (UDP)
Connectionless protocol.
Faster but does not guarantee delivery.
Used in real-time applications like VoIP and video streaming.
NETWORK PROTOCOLS
Hypertext Transfer Protocol (HTTP/HTTPS)
Used for communication between web browsers and servers.
HTTPS is the secure version with encryption via TLS/SSL.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", 12345))
s.listen(5)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(False) # Set non-blocking mode
s.bind(("localhost", 12345))
s.listen(5)
try:
conn, addr = s.accept() # May raise an error if no connection
data = conn.recv(1024) # May raise an error if no data
print("Received:", data.decode())
except BlockingIOError:
BLOCKING VS. NON-BLOCKING SOCKETS
ADVANTAGES OF USING NON-BLOCKING
SOCKETS OVER BLOCKING SOCKETS
6. Prevents Deadlocks
In blocking mode, if one socket is waiting for data, it can freeze the entire program if
not properly handled.
Non-blocking mode prevents this by ensuring the program continues executing.
Use Cases of Non-Blocking Sockets
✔ High-performance web servers (e.g., Nginx, Node.js)
✔ Online gaming and multiplayer applications
✔ Real-time messaging (WhatsApp, Slack, Discord)
✔ Stock trading systems (low-latency, high-speed)
✔ IoT and embedded systems with limited resources
ADVANTAGES OF USING NON-BLOCKING
SOCKETS OVER BLOCKING SOCKETS
while True:
client_socket, addr = server_socket.accept() # Accept a connection
print(f"Connection from {addr}")
while True:
data, addr = server_socket.recvfrom(1024)
print(f"Received from {addr}: {data.decode()}")
server_socket.sendto(b"Hello, UDP Client!", addr)
SOCKET PROGRAMMING
UDP Server
import socket
while True:
data, addr = server_socket.recvfrom(1024)
print(f"Received from {addr}: {data.decode()}")
server_socket.sendto(b"Hello, UDP Client!", addr)
SOCKET PROGRAMMING
UDP Client
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print("Received:", data.decode())
SOCKET PROGRAMMING
SOCKET PROGRAMMING
Applications of Socket Programming
Multiplayer gaming
Pros:
Simple to implement.
Good for a low number of clients.
Cons:
High overhead due to thread creation and destruction.
Not scalable for a large number of clients.
MULTITHREADING IN NETWORK
PROGRAMMING
2.Thread Pool Model
A pool of worker threads is created in advance.
Threads pick up tasks (handling client connections) from a queue
Pros:
Reduces thread creation overhead.
More scalable than thread-per-connection.
Cons:
May require careful tuning of the thread pool size.
MULTITHREADING IN NETWORK
PROGRAMMING
3. Event-Driven Model
Uses an event loop instead of multiple threads.
Relies on non-blocking I/O operations.
Pros:
Highly scalable (e.g., handles thousands of connections).
Lower memory usage compared to thread-based models.
Cons:
More complex than multithreading
MULTITHREADING IN NETWORK PROGRAMMING
MULTITHREADING IN NETWORK
PROGRAMMING
Multithreading is a powerful tool in network programming, but choosing the right
threading model depends on the application's needs.
# Accept a connection
client_socket, addr = server_socket.accept()
print(f"Connection from {addr} established.")
import socket
# Send data
client_socket.send(b"Hello, Server!")
# Receive response
response = client_socket.recv(1024)
print(f"Server response: {response.decode()}")
Conclusion
SOCK_STREAM is used for TCP communication, ensuring reliable, ordered
data transfer.
TCP requires connection establishment (handshake) before sending data.
The server listens for incoming connections, while the client initiates
communication.
TCP sockets are commonly used in applications like web servers, messaging
apps, file transfers, and more.
ADVANCED SOCKET PROGRAMMING
UDP (SOCK_DGRAM)
UDP (User Datagram Protocol) is a connectionless protocol used for fast, low-
overhead communication.
In socket programming, the SOCK_DGRAM socket type is used to indicate a
datagram-based (packet-based) connection, meaning that data is sent in discrete
messages rather than a continuous stream.
Key Characteristics of UDP (SOCK_DGRAM)
1. Connectionless Communication
1. Unlike TCP, UDP does not establish a persistent connection before sending data.
2. The sender and receiver can communicate without a handshake.
2. Unreliable but Fast
1. UDP does not guarantee message delivery, order, or error correction.
2. If packets are lost or arrive out of order, they are not retransmitted.
ADVANCED SOCKET PROGRAMMING
1. Message-Oriented
1. Data is sent in individual datagrams, which are self-contained messages.
2. Each datagram must be received in full or not at all.
2. Low Latency & Lightweight
1. Suitable for real-time applications like video streaming, gaming, VoIP, and
DNS.
ADVANCED SOCKET PROGRAMMING
To use UDP sockets in programming, we create a socket with the SOCK_DGRAM type.
import socket
Example: UDP Server (Python)
# Create a UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
# Receive data from client
data, client_addr = server_socket.recvfrom(1024)
print(f"Received from {client_addr}: {data.decode()}")
# Send response
server_socket.sendto(b"Hello from server!", client_addr)
ADVANCED SOCKET PROGRAMMING
import socket
# Server address
server_address = ('127.0.0.1', 8080)
# Send data
client_socket.sendto(b"Hello, Server!", server_address)
# Receive response
data, server = client_socket.recvfrom(1024)
print(f"Server response: {data.decode()}")
# Close socket
client_socket.close()
ADVANCED SOCKET PROGRAMMING
ADVANCED SOCKET PROGRAMMING
ADVANCED SOCKET PROGRAMMING
Conclusion
SOCK_DGRAM is used for UDP communication, which is fast but does not
guarantee message delivery or order.
UDP is ideal for real-time applications that prioritize speed over reliability.
The server listens for datagrams, and the client sends them to the server’s address.
THANK YOU