CSC 322: NETWORK AND DISTRIBUTED PROGRAMMING
2019/2020
QUESTION ONE (30 MARKS)
a) Discuss three major problems of the client-server model (3 marks)
1. Scalability Issues: As the number of clients increases, the server may become
overloaded, leading to performance degradation.
2. Single Point of Failure: The server represents a single point of failure; if it goes down,
clients lose access to services and resources.
3. Security Vulnerabilities: Centralizing data and services makes the server a target for
attacks like DDoS, unauthorized access, or data breaches.
b) Explain challenges that a distributed computing system has when servicing users who
share information and peripheral resources (3 marks)
1. Synchronization: Ensuring consistency of shared data across distributed nodes is
complex.
2. Resource Contention: Multiple users may compete for the same peripheral resources,
leading to delays and conflicts.
3. Network Latency and Reliability: Communication between distributed components
may suffer due to network failures, latency, or bandwidth limitations.
c) Discuss two important advantages of three-tier client-server architecture compared with
a normal two-tier client-server architecture (4 marks)
1. Improved Scalability: Three-tier architecture separates the presentation, application, and
data layers, allowing independent scaling of each tier to handle growing demands.
2. Enhanced Maintainability: Changes in one layer (e.g., database or user interface) can
be made without impacting other layers, simplifying maintenance and updates.
d) List the steps that are carried out when implementing TCP client program (6 marks)
1. Create Socket: Use socket() function to create a socket.
2. Specify Server Address: Define the server’s IP address and port number.
3. Establish Connection: Use connect() function to establish connection with the server.
4. Send Data: Use send() function to transmit data to the server.
5. Receive Data: Use recv() function to receive response from the server.
6. Close Connection: Use close() function to terminate the connection.
e) List the steps that are carried out when implementing TCP Server Program (6 marks)
1. Create Socket: Use socket() function to create a server socket.
2. Bind Address: Use bind() to assign IP address and port number to the socket.
3. Listen for Connections: Use listen() function to wait for incoming connection requests.
4. Accept Connection: Use accept() function to accept client connection requests.
5. Communicate: Use send() and recv() to exchange data with the client.
6. Close Socket: Use close() function to terminate the connection after communication is
complete.
f) Discuss four security services provided by DCE (Distributed Computing Environment) (8
marks)
1. Authentication Service: Verifies the identity of users and systems to ensure that only
authorized entities access resources.
2. Authorization Service: Controls access to resources by checking permissions and access
control lists.
3. Data Integrity Service: Ensures that data is not altered or tampered with during
transmission between systems.
4. Confidentiality Service: Provides encryption mechanisms to prevent unauthorized users
from reading sensitive data.
QUESTION TWO (20 MARKS)
a) Explain five types of sockets defined in the basic set sys/socket.h (5 marks)
1. SOCK_STREAM:
Provides reliable, two-way, connection-based byte streams (used in TCP
communication).
2. SOCK_DGRAM:
Provides connectionless, unreliable messages of a fixed maximum length (used in UDP
communication).
3. SOCK_RAW:
Provides raw network protocol access, allowing custom protocol implementation.
4. SOCK_SEQPACKET:
Provides reliable, sequenced, connection-based transmission of datagrams with fixed
maximum length.
5. SOCK_RDM (Reliable Datagram):
Provides a reliable datagram layer that does not guarantee ordering of message delivery.
b) Explain why we should consider fault-tolerance in a networked world, and list four
techniques used in network fault-tolerance (5 marks)
Why consider fault-tolerance:
Fault-tolerance ensures that a network continues to operate correctly even in the event of
component failures. In a networked environment where services are interdependent, a failure can
cause significant disruptions, loss of data, or downtime if not properly managed.
Four techniques used in network fault-tolerance:
1. Redundancy:
Implementing duplicate hardware (servers, network paths) to take over if one fails.
2. Failover Systems:
Automatic switching to a standby system or network in case the primary system fails.
3. Load Balancing:
Distributing network traffic across multiple servers to ensure no single point of failure.
4. Error Detection and Correction:
Using mechanisms like checksums and parity checks to detect and correct errors in
transmission.
c) Discuss five DCE (Distributed Computing Environment) services that provide tools with
which software developers can create end-user applications and system software products
for distributed computing (10 marks)
1. Remote Procedure Call (RPC) Service:
Enables communication between distributed applications by allowing a program to
execute procedures on another machine as if they were local.
2. Directory Service:
Provides a centralized database that stores information about network resources, such as
servers and users, simplifying resource location and management.
3. Security Service:
Offers authentication, authorization, and secure communication to ensure that only
authorized users and applications can access network resources.
4. Time Service:
Synchronizes the system clocks of all machines in a distributed environment to ensure
consistency in time-dependent operations.
5. Thread Service:
Supports multithreading by allowing concurrent execution of tasks within distributed
applications, improving efficiency and responsiveness.
QUESTION THREE (20 MARKS)
a) List the essential components of Java client-server communication (4 marks)
1. Socket:
Provides the endpoint for communication between client and server.
2. ServerSocket:
On the server side, it listens for incoming client connection requests.
3. InputStream/OutputStream:
Used to read from and write data to the socket (client-server communication channels).
4. Data Streams (DataInputStream, DataOutputStream, BufferedReader,
PrintWriter):
Facilitate the actual reading and writing of data in a more convenient way.
b) List the steps of setting up a datagram client (4 marks)
1. Create a DatagramSocket:
Initialize a DatagramSocket object to send the datagram packet.
2. Create DatagramPacket:
Construct a DatagramPacket with the data, destination IP address, and port number.
3. Send DatagramPacket:
Use the send() method of DatagramSocket to send the packet.
4. Receive Response (Optional):
If expecting a response, prepare a buffer, create a receive DatagramPacket, and use
receive().
c) List the steps that are carried out when implementing TCP client program (6 marks)
1. Create a Socket Object:
Instantiate a Socket with the server’s IP address and port number.
2. Obtain OutputStream & InputStream:
Get the output stream to send data and input stream to receive data from the server.
3. Send Request to Server:
Write data to the output stream (sending a request).
4. Read Server Response:
Read server's reply using the input stream.
5. Close Streams and Socket:
Properly close both input/output streams and the socket connection.
6. Handle Exceptions:
Manage exceptions like IOException to ensure smooth operation.
d) Describe three files that a developer has to supply to build a basic DCE application (6
marks)
1. Interface Definition File (.idl):
Contains the interface definitions written in Interface Definition Language (IDL) used by
the DCE RPC mechanism to define how procedures can be called remotely.
2. Server Implementation File:
Includes the actual implementation of the server-side functions/procedures as defined in
the .idl file.
3. Client Application File:
Contains the client-side code which calls the remote procedures and interacts with the
server, following the interface defined.
a) Define distributed systems (2 marks)
A Distributed System is a collection of independent computers that appear to the users as a
single coherent system. These systems communicate and coordinate their actions through a
network, sharing resources and data.
b) In message-passing communication, a message is sent and received by explicitly
executing two primitives. With the aid of a diagram, explain the execution of these two
primitives (8 marks)
Explanation:
The two primitives in message-passing communication are:
1. Send (Message)
○ The sender process sends a message to a specific receiver process.
○ Syntax: send(destination, message)
2. Receive (Message)
○ The receiver process waits to receive the message sent.
○ Syntax: receive(source, message)
Diagram:
lua
CopyEdit
+------------+ +------------+
| Sender | | Receiver |
| Process A | | Process B |
+------------+ +------------+
| |
| send(destination, message) |
+---------------------------------------------> |
| |
| receive(source, message)
| |
Explanation Flow:
● Process A (Sender) executes the send primitive to deliver a message to Process B
(Receiver).
● Process B waits for the message using the receive primitive and processes it upon arrival.
c) Define distributed system and explain four key purposes of distributed systems (10
marks)
Definition:
A Distributed System is a network of autonomous computers that communicate and coordinate
with each other to achieve a common goal, appearing as a single system to the end-users.
Key Purposes of Distributed Systems:
1. Resource Sharing:
Distributed systems enable sharing of hardware (printers, storage), software, and data
resources across multiple systems seamlessly.
2. Scalability:
They are designed to easily scale up by adding more machines without disrupting the
overall functionality.
3. Fault Tolerance & Reliability:
The system continues functioning even if one or more nodes fail, providing high
availability and reliability.
4. Transparency:
Distributed systems provide various forms of transparency (location, access, failure,
concurrency, replication) to hide the complexity from the users, making interaction
smooth and uniform.
QUESTION FIVE (20 MARKS)
a) In addition to providing services for business logic and applications, discuss two key
services the application tier should provide (2 marks)
1. Security Services:
○ The application tier should ensure authentication, authorization, and data
encryption to protect sensitive information and maintain system integrity.
2. Transaction Management:
○ It should provide mechanisms to handle transactions, ensuring consistency,
atomicity, isolation, and durability (ACID properties).
b) Discuss three phases in the construction and use of an RPC-based distributed
application (6 marks)
1. Client Stub Creation:
○ The developer writes client-side stubs that marshal (pack) procedure arguments
into a message format suitable for transmission.
2. Server Stub Creation:
○ The developer writes server-side stubs that unmarshall (unpack) received
messages and invoke the appropriate procedure on the server.
3. Communication Phase:
○ The client sends a request via the client stub; the server stub receives it, processes
the procedure, and returns the result. Middleware handles transport and
communication between stubs.
c) Differentiate between TCP, UDP, IP protocols defined in the TCP/IP protocol suite (6
marks)
Protocol Description Key Features
TCP (Transmission A connection-oriented protocol ensuring - Reliable, ordered
Control Protocol) reliable data transmission. delivery
- Error checking
- Flow control
UDP (User Datagram A connectionless protocol used for fast, - Unreliable, no
Protocol) lightweight transmission without guarantee
guarantee of delivery. - Low overhead, faster
- No connection
establishment
IP (Internet Protocol) Handles addressing and routing of - Connectionless
packets between devices in a network. - Provides logical
addressing (IP
addresses)
- No reliability features
d) Discuss the steps required for connection-oriented communications to occur (6 marks)
1. Connection Establishment (Three-Way Handshake):
○ SYN: The client sends a SYN (synchronize) packet to the server.
○ SYN-ACK: The server responds with a SYN-ACK packet.
○ ACK: The client replies with an ACK packet, establishing the connection.
2. Data Transfer:
○ After the connection is established, data is transmitted reliably between client and
server with acknowledgment and sequencing.
3. Connection Termination:
○ Either side can initiate termination using FIN and ACK packets, ensuring both
parties agree to close the connection gracefully.
2017/2018
QUESTION ONE (30 MARKS)
a) Describe the following Terms as used in Distributed Computing Environment (10
Marks)
i) Distributed System (2 Marks):
A distributed system is a collection of independent computers that appear to users as a single
coherent system. These systems communicate and coordinate their actions by passing messages
over a network.
ii) Concurrency (2 Marks):
Concurrency refers to the ability of the distributed system to allow multiple processes to execute
simultaneously, ensuring tasks progress independently while sharing resources efficiently.
iii) System (2 Marks):
A system is a set of interconnected components working together toward a common goal. In
distributed systems, it refers to a collection of hardware, software, and networking components
designed to perform tasks.
iv) Synchronization (2 Marks):
Synchronization is the coordination of concurrent processes to ensure data consistency and
correctness. It prevents conflicts like race conditions by managing access to shared resources.
v) Remote Procedure Call (RPC) (2 Marks):
RPC is a protocol that allows a program to execute a procedure on a remote server as if it were a
local procedure, abstracting the details of network communication.
b) Explain any 5 Challenges Facing Designers of Distributed Systems (10 Marks)
1. Fault Tolerance:
Handling hardware or network failures without disrupting the entire system.
2. Security:
Ensuring data confidentiality, integrity, and authentication over open networks.
3. Scalability:
Designing systems to efficiently handle growth in users, data, and resources.
4. Resource Management:
Efficient allocation and sharing of resources like processing power, memory, and
network bandwidth.
5. Latency and Bandwidth Management:
Managing delays and limited network capacity to ensure smooth communication and
performance.
c) Discuss 5 Issues with Distributed Systems (10 Marks)
1. Transparency:
Hiding complexity such as location, access, and replication from users.
2. Heterogeneity:
Managing different hardware, operating systems, and network protocols.
3. Resource Sharing:
Coordinating multiple users accessing shared resources without conflict.
4. Security Issues:
Protecting the system against unauthorized access, data breaches, and attacks.
5. Communication Failures:
Handling message loss, delays, or duplication during inter-process communication.
QUESTION TWO (20 MARKS)
a) Describe the term Transaction (4 Marks)
A transaction is a sequence of operations performed as a single logical unit of work in a
database or distributed system. It ensures that either all operations are executed successfully or
none at all, preserving data integrity. A transaction adheres to the ACID properties:
● Atomicity: Ensures that all steps in the transaction complete successfully or the system
rolls back to the previous state.
● Consistency: Guarantees that the system remains in a valid state before and after the
transaction.
● Isolation: Ensures that concurrent transactions do not interfere with each other.
● Durability: Once committed, the transaction’s results are permanent even in case of
failures.
b) Explain the following concepts in relation to Transparency (8 Marks)
i) Access Transparency (2 Marks)
This type of transparency hides differences in data access mechanisms, allowing users to access
local and remote resources in the same way, without knowing their physical location or access
method.
ii) Concurrency Transparency (2 Marks)
Concurrency transparency ensures that multiple processes or users can access shared resources
simultaneously without interference, making the system behave as though each user has
exclusive access.
iii) Failure Transparency (2 Marks)
Failure transparency enables the system to recover from hardware or software failures without
users noticing. It ensures that the system can mask failures and continue functioning properly.
iv) Migration Transparency (2 Marks)
Migration transparency allows resources, processes, or tasks to move from one physical location
to another within the system without affecting users or applications.
c) Discuss the Sleeping Barber Problem in Classical IPC Problems and give at least two
application areas (8 Marks)
Sleeping Barber Problem:
It is a classic synchronization problem in Inter-Process Communication (IPC). It models a
barber shop with:
● One barber
● One barber chair
● A waiting room with a limited number of chairs
Scenario:
● If no customers, the barber sleeps.
● If a customer arrives and all chairs are full, the customer leaves.
● If a customer arrives and chairs are available, they wait; the barber wakes up if asleep and
serves them.
Purpose:
The problem demonstrates synchronization challenges such as managing access to limited
resources (chairs) and coordination between processes (barber & customers).
Application Areas:
1. Operating Systems:
Managing process scheduling where limited CPU slots (barber chairs) are allocated to
processes (customers).
2. Network Servers:
Handling multiple client connections with limited server threads/resources. If too many
connections arrive, excess requests are dropped or queued.
QUESTION THREE (20 MARKS)
a) Advantages and Disadvantages of Distributed Systems over Centralized Systems (8
Marks)
Advantages Disadvantages
1. Scalability: Easy to add more 1. Complexity: More difficult to design and
nodes/resources to handle increased load. maintain due to multiple nodes.
2. Fault Tolerance: Failure of one node does 2. Security Risks: Data transmitted over the
not bring down the entire system. network increases vulnerability.
3. Resource Sharing: Resources like 3. Synchronization Issues: Ensuring data
printers, databases, and files can be shared. consistency across nodes is complex.
4. Geographical Distribution: Supports 4. Latency: Network communication
remote access and decentralized operations. introduces delays compared to local access.
b) Explain the Following Distributed Models (6 Marks)
i) Architectural Models (2 Marks)
Defines how components are structured and how they interact. Examples include:
● Client-Server Model
● Peer-to-Peer Model
● Three-Tier Model
ii) Fundamental Models (2 Marks)
Describes system behavior in terms of interaction patterns:
● Interaction Models: Synchronous/asynchronous communication.
● Failure Models: Defines how components may fail.
● Security Models: Specifies security threats and mitigation.
iii) Physical Models (2 Marks)
Represents the physical arrangement of hardware components:
● Nodes: Physical machines (servers, clients).
● Network Topology: The way nodes are connected.
● Data Storage Distribution.
c) Three Types of Distributed Systems (6 Marks)
1. Distributed File Systems (e.g., NFS, Hadoop HDFS):
Provide transparent access to files distributed across multiple servers.
2. Distributed Databases (e.g., Google Spanner, Cassandra):
Databases stored across multiple nodes with synchronization mechanisms.
3. Distributed Computing Systems (e.g., SETI@home, Grid Computing):
Tasks divided among multiple computers to perform large computations
QUESTION FOUR (20 MARKS)
a) Network Layers in the Context of Network Protocols (8 Marks)
The OSI Model layers:
1. Physical Layer: Transmission of raw bitstreams over a medium (e.g., Ethernet cables).
2. Data Link Layer: Error detection/correction, MAC addressing (e.g., Switches).
3. Network Layer: Routing, addressing (IP protocol).
4. Transport Layer: Reliable data delivery, flow control (TCP, UDP).
5. Session Layer: Manages sessions (logical connections).
6. Presentation Layer: Data translation, encryption, compression.
7. Application Layer: End-user applications (HTTP, FTP, DNS).
b) Differentiate between the following Terms (4 Marks)
i) Message Passing:
Communication method where processes send/receive messages explicitly without shared
memory.
ii) Remote Procedure Call (RPC):
Abstracts communication by allowing a program to execute procedures on a remote system as if
they were local calls.
c) Discuss DOS in Detail (8 Marks)
Denial of Service (DoS) Attack:
● Definition:
An attack aimed at making a network or service unavailable by overwhelming it with
traffic or resource requests.
● Types:
○ Flooding Attacks: E.g., ICMP flood, SYN flood.
○ Application-Layer DoS: Overloading specific application processes.
● Impact:
Downtime, revenue loss, degraded performance, security breaches.
● Mitigation Techniques:
Firewalls, Intrusion Detection Systems (IDS), load balancers, rate limiting, anti-DDoS
services (e.g., Cloudflare).
QUESTION FIVE (20 MARKS)
a) Describe Distributed System in the Context of an ERP System (6 Marks)
A Distributed ERP System is an Enterprise Resource Planning solution where modules
(finance, HR, inventory, etc.) are spread across different servers or geographical locations.
Benefits:
● Improved Performance: Load distributed.
● Fault Tolerance: Failure of one module doesn't crash entire system.
● Flexibility: Easier scaling and integration with external systems.
● Remote Access: Supports branches in different locations.
b) Discuss Middleware (6 Marks)
Middleware is software that acts as an intermediary between applications and network services
in distributed systems.
Functions:
1. Communication Management: Handles message passing (e.g., CORBA, RPC).
2. Security: Authentication, encryption.
3. Transaction Management: Ensures ACID properties.
4. Resource Access: Provides APIs for database/file access.
5. Interoperability: Facilitates communication between heterogeneous systems
c) Write a program and discuss about the reader,s and writer,s, problem
Program: Readers-Writers Problem (Using Python threading)
python
CopyEdit
import threading
import time
# Shared variables
readers_count = 0
resource_lock = threading.Lock()
readers_count_lock = threading.Lock()
# Reader function
def reader(id):
global readers_count
while True:
time.sleep(1) # Simulate reading interval
# Entry Section
readers_count_lock.acquire()
readers_count += 1
if readers_count == 1:
resource_lock.acquire() # First reader locks resource
readers_count_lock.release()
# Critical Section
print(f"Reader {id} is reading.")
time.sleep(2) # Simulate reading time
# Exit Section
readers_count_lock.acquire()
readers_count -= 1
if readers_count == 0:
resource_lock.release() # Last reader releases resource
readers_count_lock.release()
# Writer function
def writer(id):
while True:
time.sleep(3) # Simulate writing interval
# Entry Section
resource_lock.acquire()
# Critical Section
print(f"Writer {id} is writing.")
time.sleep(2) # Simulate writing time
# Exit Section
resource_lock.release()
# Create reader and writer threads
reader_threads = [threading.Thread(target=reader, args=(i,)) for i in range(3)]
writer_threads = [threading.Thread(target=writer, args=(i,)) for i in range(2)]
# Start threads
for t in reader_threads + writer_threads:
t.start()
# Join threads (optional for infinite simulation)
for t in reader_threads + writer_threads:
t.join()
Discussion: Readers-Writers Problem
Problem Definition:
● Readers-Writers Problem is a classic synchronization problem where:
○ Multiple readers can read the shared resource simultaneously.
○ Writers require exclusive access (no other readers/writers during write).
Solution Approach in Program:
1. Locks Used:
○ resource_lock: Ensures exclusive access for writers.
○ readers_count_lock: Protects access to readers_count variable (to avoid race
condition).
2. Reader Logic:
○ Entry Section:
■ Increment readers_count.
■ If first reader, lock the resource to prevent writers.
○ Critical Section: Read the resource.
○ Exit Section:
■ Decrement readers_count.
■ If last reader, release the resource lock.
3. Writer Logic:
○ Entry Section: Acquires resource_lock to get exclusive access.
○ Critical Section: Writes to the resource.
○ Exit Section: Releases the lock.
Key Concepts:
Concept Explanation
Mutual Exclusion Writers get exclusive access to prevent data inconsistency.
Concurrent Multiple readers can read at the same time without conflict.
Reading
Synchronization Locks ensure safe access to shared variables and resource.
Starvation If writers wait indefinitely because of continuous readers (can be
Concern solved by adding fairness logic).
2016/2017
QUESTION ONE (30 MARKS)
a) What is thread synchronization? (2 marks)
Thread synchronization is a mechanism to control the access of multiple threads to shared
resources (like variables, files, memory) in order to prevent data inconsistency and ensure that
only one thread accesses the critical section at a time.
b) Explain the importance of thread priorities in Java. (3 marks)
In Java, thread priorities help the thread scheduler determine the order in which threads are
executed. The priorities range from MIN_PRIORITY (1) to MAX_PRIORITY (10), with the
default being NORM_PRIORITY (5).
Importance:
1. Better Resource Utilization: Critical tasks can be given higher priority.
2. Control Execution Order: Ensures important threads complete sooner.
3. Improves Performance: Prevents unnecessary delays by prioritizing essential threads.
However, thread priorities may not guarantee behavior consistency across different platforms due
to platform-dependent scheduling.
c) Briefly explain five states of a thread in its life cycle. In your answer show how the
thread transits from one state to another. (5 marks)
State Description Transition
New Thread object created but not Thread.start() moves it to Runnable.
started.
Runnable Ready to run, waiting for CPU Scheduled by thread scheduler, moves
scheduling. to Running.
Running Actively executing the task. After completion or interruption,
moves to Terminated or
Blocked/Waiting.
Blocked/Waiting Waiting for a resource or signal When resource/signal becomes
(e.g., waiting for lock, wait() available, moves back to Runnable.
method).
Terminated Thread has finished execution or End state.
is terminated due to error.
d) Give a brief description of a client-server programming model. (5 marks)
Client-Server Model:
● A network architecture where clients request services, and servers provide those
services.
● The server listens for incoming client requests, processes them, and returns the response.
● Clients can be multiple users/applications interacting simultaneously with a centralized
server.
Examples:
● Web browsing (Client: Browser, Server: Web server),
● Database access (Client: Application, Server: Database server).
e) Write a simple Java program that can read a host name and convert it to an IP address.
(5 marks)
java
CopyEdit
import java.net.*;
public class HostToIP {
public static void main(String[] args) {
try {
String hostName = "www.google.com";
InetAddress address = InetAddress.getByName(hostName);
System.out.println("Host: " + hostName);
System.out.println("IP Address: " + address.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Host not found: " + e.getMessage());
f) Describe five services of CORBA. (5 marks)
1. Naming Service: Allows clients to find object references using human-readable names.
2. Event Service: Provides asynchronous communication by distributing events to multiple
consumers.
3. Transaction Service: Supports distributed transactions ensuring atomicity and
consistency.
4. Security Service: Manages authentication, authorization, confidentiality, and integrity.
5. Lifecycle Service: Provides mechanisms for creating, copying, deleting, and moving
CORBA objects.
a) Write a Java code segment that will create a TCP client and TCP server that listens to
client requests. The client will send the message "Hello, are you up!" The server will then
respond with the message "Yes I am up and listeningP' (Hint: you will use the Socket class
and ServerSocket class). (12 marks)
TCP Server (Python)
python
CopyEdit
import socket
# Server configuration
HOST = '127.0.0.1' # Localhost
PORT = 5000 # Port to listen on
# Create server socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen()
print("Server is up and listening...")
# Accept a connection
conn, addr = server_socket.accept()
print(f"Connected by {addr}")
# Receive data from client
data = conn.recv(1024).decode()
print(f"Received from client: {data}")
# Send response to client
response = "Yes I am up and listening"
conn.sendall(response.encode())
# Close connections
conn.close()
server_socket.close()
TCP Client (Python)
python
CopyEdit
import socket
# Server configuration
HOST = '127.0.0.1' # Server's hostname or IP address
PORT = 5000 # Server's port
# Create client socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
# Send message to server
message = "Hello, are you up!"
client_socket.sendall(message.encode())
# Receive response from server
response = client_socket.recv(1024).decode()
print(f"Received from server: {response}")
# Close connection
client_socket.close()
QUESTION THREE (20 MARKS)
a) Explain three differences between broadcasting and multicasting. Show their differences
in Java code implementations. (10 marks)
Broadcasting Multicasting
Sends data to all hosts on a network Sends data to a group of hosts
Uses a broadcast address (e.g., Uses multicast IP range (224.0.0.0 to
255.255.255.255) 239.255.255.255)
Higher network traffic due to all hosts Efficient, only hosts in the group receive data
receiving data
Java Code Implementation Differences:
Broadcast Example (Java):
java
CopyEdit
import java.net.*;
public class BroadcastSender {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
socket.setBroadcast(true);
String message = "Broadcast message!";
byte[] buffer = message.getBytes();
InetAddress address = InetAddress.getByName("255.255.255.255");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 5000);
socket.send(packet);
socket.close();
Multicast Example (Java):
java
CopyEdit
import java.net.*;
public class MulticastSender {
public static void main(String[] args) throws Exception {
MulticastSocket socket = new MulticastSocket();
String message = "Multicast message!";
byte[] buffer = message.getBytes();
InetAddress group = InetAddress.getByName("230.0.0.1");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, 4446);
socket.send(packet);
socket.close();
b) Write a ping-pong client and server application. When a client sends a ping message to
the server, the server will respond with a pong message. Other messages sent by the client
can be safely dropped by the server. (10 marks)
Server Code (Java):
java
CopyEdit
import java.io.*;
import java.net.*;
public class PongServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server is listening...");
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String message;
while ((message = in.readLine()) != null) {
if (message.equalsIgnoreCase("ping")) {
out.println("pong");
} else {
out.println("Message dropped");
clientSocket.close();
serverSocket.close();
Client Code (Java):
java
CopyEdit
import java.io.*;
import java.net.*;
public class PingClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 5000);
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
System.out.println("Enter message (ping to get pong): ");
String userInput;
while ((userInput = input.readLine()) != null) {
out.println(userInput);
System.out.println("Server response: " + in.readLine());
socket.close();
Would you like the Python version of the Ping-Pong app as well?
4o
You said:
yes
ChatGPT said:
Here’s a simple Ping-Pong Client & Server application in Python, using TCP sockets:
🟢 Server Code (Python):
python
CopyEdit
import socket
def start_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 5000))
server_socket.listen(1)
print("Server is listening...")
conn, addr = server_socket.accept()
print(f"Connected to {addr}")
while True:
data = conn.recv(1024).decode()
if not data:
break
print(f"Received: {data}")
if data.lower() == "ping":
conn.send("pong".encode())
else:
conn.send("Message dropped".encode())
conn.close()
server_socket.close()
start_server()
🟢 Client Code (Python):
python
CopyEdit
import socket
def start_client():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 5000))
while True:
message = input("Enter message (type 'exit' to quit): ")
if message.lower() == 'exit':
break
client_socket.send(message.encode())
response = client_socket.recv(1024).decode()
print(f"Server response: {response}")
client_socket.close()
start_client()
✅ How it works:
● Server:
○ Listens on port 5000.
○ When it receives "ping", replies "pong".
○ Any other message → replies "Message dropped".
● Client:
○ Sends messages to the server.
○ Prints server responses.
○ Type 'exit' to stop the client.
b) Explain what a socket is and briefly discuss the three types of sockets.
(10 Marks)
What is a Socket?
A socket is an endpoint for sending and receiving data across a computer network. It is a
combination of an IP address and a port number, allowing communication between two
machines (client and server) over a network.
Sockets provide a mechanism for establishing communication links between different processes,
possibly on different machines, and support different communication protocols (e.g., TCP, UDP).
Three Types of Sockets:
1. Stream Sockets (SOCK_STREAM):
● Protocol Used: TCP (Transmission Control Protocol)
● Characteristics:
○ Provides reliable, connection-oriented communication.
○ Ensures data integrity, ordered delivery, and error checking.
○ Suitable for applications where data must arrive intact and in order, e.g., HTTP,
FTP, email protocols.
● Example Use Case: Web browsers communicating with web servers.
2. Datagram Sockets (SOCK_DGRAM):
● Protocol Used: UDP (User Datagram Protocol)
● Characteristics:
○ Provides connectionless, unreliable communication.
○ Data is sent in discrete packets called datagrams.
○ No guarantee of delivery, ordering, or duplicate protection.
○ Faster and low-overhead compared to stream sockets.
● Example Use Case: Live video streaming, VoIP, online gaming.
3. Raw Sockets (SOCK_RAW):
● Protocol Used: Direct access to lower-level protocols (e.g., IP, ICMP).
● Characteristics:
○ Allows applications to directly access underlying transport protocols.
○ Mainly used for network diagnostic tools like ping, traceroute, and for custom
protocol development.
○ Requires administrative/root privileges to use due to security concerns.
● Example Use Case: Network monitoring, packet sniffing.