0% found this document useful (0 votes)
1 views45 pages

Network Programming

The document provides an overview of network programming, focusing on key concepts such as the client-server model, networking protocols (TCP, UDP, HTTP, FTP), and socket programming. It discusses blocking vs. non-blocking sockets, their advantages, and the use of multithreading in network applications. Additionally, it covers advanced socket programming techniques, including the characteristics of TCP and UDP protocols.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views45 pages

Network Programming

The document provides an overview of network programming, focusing on key concepts such as the client-server model, networking protocols (TCP, UDP, HTTP, FTP), and socket programming. It discusses blocking vs. non-blocking sockets, their advantages, and the use of multithreading in network applications. Additionally, it covers advanced socket programming techniques, including the characteristics of TCP and UDP protocols.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

CHRIST APOSTOLIC

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.

File Transfer Protocol (FTP)


 Used for transferring files between computers on a network.

Domain Name System (DNS)


 Resolves human-readable domain names to IP addresses.
SOCKETS AND SOCKET PROGRAMMING
 Sockets are the endpoints of a two-way communication link between two programs
running on a network.
 Sockets can be created using programming languages like C, Java, and Python.
 They enable processes to communicate with each other, either on the same machine or
over a network, using protocols like TCP (Transmission Control Protocol) and UDP
(User Datagram Protocol).
What is a Socket?
A socket is an interface between the application layer and the transport layer. It acts as a
bridge between application processes and network communication protocols.
Types of Sockets
1. Stream Sockets (TCP Sockets) – Reliable, connection-oriented communication.
2. Datagram Sockets (UDP Sockets) – Unreliable, connectionless communication.
3. Raw Sockets – Used for low-level network access, often requiring administrative privileges.
BLOCKING VS. NON-BLOCKING SOCKETS
 Sockets are endpoints for communication between two machines. When dealing with
sockets in network programming, they can operate in blocking or non-blocking
modes.
 Blocking Sockets: In blocking mode, the socket operations (such as recv(), send(),
accept(), and connect()) wait until the operation completes before returning.
 This means the program execution is paused until data is received, sent, or a
connection is established.
 Example Scenario: If a recv() call is made and no data is available, the program will
halt until data arrives.
 Use Case: Suitable for simple applications where blocking behavior is acceptable,
like sequential communication.
BLOCKING VS. NON-BLOCKING SOCKETS

Blocking Sockets ( CODE)


import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", 12345))
s.listen(5)

conn, addr = s.accept() # Blocks until a client connects


data = conn.recv(1024) # Blocks until data is received
print("Received:", data.decode())
BLOCKING VS. NON-BLOCKING SOCKETS
 Non-Blocking Sockets: In non-blocking mode, socket operations return immediately,
even if they haven't completed their tasks.

 Instead of waiting, they raise an exception (BlockingIOError in Python) if no data


is available or the operation cannot proceed.

 Example Scenario: If recv() is called and no data is available, it immediately returns


an error instead of waiting.

 Use Case: Useful for high-performance servers (e.g., event-driven applications


using select(), poll(), or asyncio in Python).
BLOCKING VS. NON-BLOCKING SOCKETS

Non-Blocking Sockets ( CODE)

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

Non-blocking sockets provide several advantages, especially in high-


performance and scalable network applications. Here are the key benefits:
1. Improved Performance and Efficiency
• Non-blocking sockets allow an application to handle multiple connections
simultaneously without being stalled by a single slow operation.
• The program doesn't wait for data; instead, it can continue executing other
tasks and check back later.
Example: A web server handling thousands of connections wouldn't freeze
waiting for each client to send a request. Instead, it processes other requests
while waiting.
ADVANTAGES OF USING NON-BLOCKING
SOCKETS OVER BLOCKING SOCKETS

2. Asynchronous and Event-Driven Programming:


Ideal for event-driven architectures where the program responds to events (e.g., new
data, new connections) rather than waiting for a function to complete.
Works well with event loops (select(), poll(), epoll(), or asyncio in Python).
3. No Threading Overhead
Blocking sockets require multiple threads to handle multiple connections, leading
to context-switching overhead.
Non-blocking sockets allow single-threaded architectures, reducing resource usage.
Example: Instead of creating a new thread per connection (which can be inefficient),
a non-blocking server can manage many clients in one thread.
ADVANTAGES OF USING NON-BLOCKING
SOCKETS OVER BLOCKING SOCKETS

4. Faster Response Time


The application remains responsive and doesn't freeze while waiting for I/O
operations.
This is critical in real-time applications like gaming, financial trading, and
chat applications.
5. Scalability for Large Applications
Works efficiently with thousands of concurrent
connections (e.g., chat servers, APIs, microservices).
Used in frameworks like Node.js (event-driven, non-blocking
I/O).
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

When to Use Blocking Sockets Instead?

Small, simple applications (e.g., basic TCP clients) When


handling only one connection at a time

If simplicity is preferred over performance


SOCKET PROGRAMMING
 Socket programming is the process of using sockets to establish communication
between two networked devices.
Key Socket Methods
SOCKET PROGRAMMING
TCP Server (Phyton)
import socket
# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind to an address and port


server_socket.bind(('0.0.0.0', 12345))

# Start listening for connections


server_socket.listen(5)
print("Server is listening on port 12345...")

while True:
client_socket, addr = server_socket.accept() # Accept a connection
print(f"Connection from {addr}")

client_socket.send(b"Hello, Client!") # Send data


client_socket.close() # Close connection
SOCKET PROGRAMMING
TCP Client (Phyton)
import socket
client_socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
client_socket.connect(('127.0.0.1', 12345)) # Connect to the
server
data = client_socket.recv(1024) # Receive data
print("Received:", data.decode())
client_socket.close()
SOCKET PROGRAMMING
import socket

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


server_socket.bind(('0.0.0.0', 12345))

print("UDP Server listening on port 12345...")

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

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


server_socket.bind(('0.0.0.0', 12345))

print("UDP Server listening on port 12345...")

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)

client_socket.sendto(b"Hello, Server!", ('127.0.0.1', 12345)) # Send data


data, addr = client_socket.recvfrom(1024) # Receive data

print("Received:", data.decode())
SOCKET PROGRAMMING
SOCKET PROGRAMMING
Applications of Socket Programming

Web servers and browsers (HTTP)

Chat applications (WhatsApp, Messenger)

Multiplayer gaming

File transfers (FTP, SFTP)

IoT device communication


MULTITHREADING IN NETWORK PROGRAMMING
 Multithreading is an essential concept in network programming that allows multiple
tasks to be executed concurrently within a single application.
 It is particularly useful for handling multiple client connections, improving
responsiveness, and maximizing resource utilization
Why Use Multithreading in Network Programming?
1. Concurrency: Allows multiple clients to be served simultaneously without blocking
each other.
2. Improved Performance: By utilizing multiple CPU cores, it enhances the efficiency
of network applications.
3. Responsiveness: Keeps the application responsive by handling tasks in parallel.
Better Resource Utilization: Reduces idle time by overlapping I/O operations with
computation
MULTITHREADING IN NETWORK
PROGRAMMING

There are different ways to implement multithreading in network applications:


1.Thread-Per-Connection Model
 A new thread is created for each incoming client connection.
 Each thread independently handles client requests.

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.

For small-scale applications, a thread-per-connection model works fine, while


thread pools improve efficiency for moderate loads.

 For handling thousands of clients efficiently, event-driven programming (async) is


the best choice.
ADVANCED SOCKET PROGRAMMING

 Advanced socket programming goes beyond basic client-server communication,


handling more complex networking scenarios such as asynchronous
communication, multiplexing, non-blocking sockets, and secure connect
1. Types of Sockets
 TCP (SOCK_STREAM) – Reliable, connection-oriented.
 UDP (SOCK_DGRAM) – Faster, connectionless, but unreliable.
 Raw Sockets – Used for custom packet handling.
 UNIX Domain Sockets – Used for inter-process communication (IPC).
ADVANCED SOCKET PROGRAMMING
1.TCP (SOCK_STREAM)
 In network programming, TCP (Transmission Control Protocol) is a connection-
oriented protocol that provides reliable, ordered, and error-checked delivery of data.
 When using TCP in socket programming, the SOCK_STREAM socket type is used
to indicate a stream-based connection.
Key Characteristics of TCP (SOCK_STREAM)
1.Connection-Oriented
1. Before data transfer, a connection must be established using a
three-way handshake between the client and the server.
2. The connection is closed only when both parties have finished
communication.
ADVANCED SOCKET PROGRAMMING

2.Reliable Data Transfer


1. TCP ensures that all packets are received correctly and in order.
2. It uses acknowledgments (ACKs) and retransmissions to prevent data loss.
3.Stream-Based Communication
3. Data is sent as a continuous stream, rather than fixed-size packets.
4. The receiver can process data as a byte stream.
4.Error Checking & Flow Control
5. TCP detects errors and handles lost packets.
6. It manages flow control to prevent the sender from overwhelming the receiver.
ADVANCED SOCKET PROGRAMMING

Using TCP (SOCK_STREAM) in Network Programming

To use TCP sockets in programming, we create a socket with


the SOCK_STREAM type.
SOCK_STREAM type.
Example: TCP Server (Python)
import socket

# Create a TCP socket


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

# Bind the socket to an address and port


server_socket.bind(('0.0.0.0', 8080))

# Listen for incoming connections


server_socket.listen(5)
print("Server is listening on port 8080...")

# Accept a connection
client_socket, addr = server_socket.accept()
print(f"Connection from {addr} established.")

# Receive and send data


data = client_socket.recv(1024) # Receive up to 1024 bytes
print(f"Received: {data.decode()}")

client_socket.send(b"Hello from server!") # Send response

# Close the connection


client_socket.close()
SOCK_STREAM type.
Example: TCP Client (Python)

import socket

# Create a TCP socket


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

# Connect to the server


client_socket.connect(('127.0.0.1', 8080))

# Send data
client_socket.send(b"Hello, Server!")

# Receive response
response = client_socket.recv(1024)
print(f"Server response: {response.decode()}")

# Close the connection


KEY FUNCTIONS USED IN TCP SOCKET
PROGRAMMING
Using TCP (SOCK_STREAM) in Network Programming

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)

# Bind to an IP and port


server_socket.bind(('0.0.0.0', 8080))
print("UDP server is listening on port 8080...")

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

Example: UDP Client (Python)


# Create a UDP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 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.

 Unlike TCP, there is no need to establish a connection before sending data.

 The server listens for datagrams, and the client sends them to the server’s address.
THANK YOU

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy