Introduction to Distributed and Parallel
Computing
CS-302
Dr. Sanjay Saxena
Assistant Professor, CSE, IIIT Vadodara
Post doc – University of Pennsylvania, USA
PhD – Indian Institute of Technology(BHU), Varanasi
Socket Programming in Distributed System
Each socket is identified by:
•IP address
•Port number
•Protocol (TCP or UDP)
Sockets are the foundation of client–server systems.
How Socket-Based Communication Works
• In socket communication: One computer is the server, Another computer is the client
They communicate using IP address and port number
Conceptual Steps
Server side Client side
1. Create a socket 1. Create socket
2. Bind it to IP and port 2. Connect to server
3. Listen for clients 3. Send data
4. Accept client connection 4. Receive data
5. Send / receive data 5. Close socket
6. Close connection
Contd..
Python Socket Programming
Item Type Purpose Meaning
Lets Python programs talk
socket Package Provides networking functions
over network
Opens a communication
[Link]() Function Creates a new socket
door
AF_INET Constant Uses IPv4 Normal internet address
SOCK_STREAM Constant Uses TCP Reliable connection
bind() Function Assigns IP & port Gives server an address
Server waits for
listen() Function Waits for clients
connections
Opens connection for one
accept() Function Accepts client
client
Client knocks on server
connect() Function Client connects to server
door
send() Function Sends data Sends message
recv() Function Receives data Gets message
Contd..
encode() Method Converts text to bytes Network uses bytes
decode() Method Converts bytes to text Readable message
close() Function Closes socket Ends communication
"localhost" Address Local computer Same machine
12345 Port Application number Identifies program
open() Function Opens file Reads file for sending
read() Function Reads file content Gets file data
Example: Simple Client–Server in Python
Server Program
import socket
# Create socket
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
# Bind IP and port
[Link](("localhost", 12345))
# Listen for client
[Link](1)
print("Server is waiting for a connection...")
# Accept client
client_socket, client_address = [Link]()
print("Connected to", client_address)
# Send message to client
client_socket.send("Hello from Server".encode())
# Close connection
client_socket.close()
[Link]()
Contd..
Client Program
import socket
# Create socket
client = [Link](socket.AF_INET, socket.SOCK_STREAM)
# Connect to server
[Link](("localhost", 12345))
# Receive message
message = [Link](1024).decode()
print("Server says:", message)
# Close socket
[Link]()
Example 2 — Two-Way Communication (Chat Style)
Server
import socket
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("localhost", 12345))
[Link](1)
print("Server waiting...")
client, addr = [Link]()
print("Connected to", addr)
message = [Link](1024).decode()
print("Client says:", message)
[Link]("Hello Client, message received!".encode())
[Link]()
[Link]()
Client Program
import socket
client = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("localhost", 12345))
[Link]("Hello Server!".encode())
reply = [Link](1024).decode()
print("Server says:", reply)
[Link]()
What is RPC?
Remote Procedure Call (RPC) allows a program to call a function on another computer as if it were a local function.
Instead of writing: You write:
send_message() result = add(5, 3)
receive_reply()
But the function runs on a remote machine.
RPC hides network communication from the programmer.
Why RPC is Needed
• Without RPC: Programmer must write socket code
• Handle messages
• Handle packet formats
• With RPC:
• Programmer only calls functions
• RPC system handles:
• Packing arguments
• Sending data
• Receiving result
• RPC makes distributed programming simple and clean.
How RPC Works (Conceptual)
When a client calls:
result = add(5, 3)
Behind the scenes:
[Link] Stub packs arguments
[Link] them over network
[Link] Stub unpacks them
[Link] runs add(5,3)
[Link] is packed and sent back
[Link] receives result
Programming Model of RPC
• RPC has three parts:
Component Role
Client Program Calls remote function
Client Stub Packs arguments
Server Stub Unpacks arguments
Server Program Executes function
RPC Runtime Sends & receives messages
RPC automatically does:
Marshalling (packing)
Unmarshalling (unpacking)
Network communication
Example
Client
• result = multiply(4, 5)
• print(result)
Server
def multiply(a, b):
return a * b
Python RPC Server Program (rpc_server.py)
def stats(numbers):
"""
from [Link] import SimpleXMLRPCServer,
Return basic stats for a list of numbers.
SimpleXMLRPCRequestHandler
XML-RPC supports lists of ints/floats.
# Optional: restrict requests to a specific path
"""
(cleaner + safer for demo)
if not numbers:
class
return {"count": 0, "sum": 0, "min": None, "max": None,
RequestHandler(SimpleXMLRPCRequestHandler):
"avg": None}
rpc_paths = ("/RPC2",)
total = sum(numbers)
def add(a, b):
return {
"""Return sum of two numbers."""
"count": len(numbers),
return a + b
"sum": total,
def multiply(a, b):
"min": min(numbers),
"""Return product of two numbers."""
"max": max(numbers),
return a * b
"avg": total / len(numbers),
def reverse_text(s):
}
"""Return reversed string."""
return s[::-1]
def main():
host = "localhost"
port = 8000
Contd..
# Create RPC server
with SimpleXMLRPCServer((host, port), requestHandler=RequestHandler, allow_none=True) as server:
server.register_introspection_functions() # enables [Link](), etc.
# Register remote functions
server.register_function(add, "add")
server.register_function(multiply, "multiply")
server.register_function(reverse_text, "reverse_text")
server.register_function(stats, "stats")
print(f"RPC Server running on [Link]
print("Waiting for RPC calls...")
server.serve_forever()
import [Link]
def main():
# Connect to the server endpoint
proxy =
RPC Client Program [Link]("[Link]
allow_none=True)
(rpc_client.py)
# Optional: discover methods (nice for teaching)
print("Available methods:", [Link]())
# Remote procedure calls (look like normal function calls!)
print("add(10, 20) =", [Link](10, 20))
print("multiply(6, 7) =", [Link](6, 7))
print("reverse_text('distributed') =",
proxy.reverse_text("distributed"))
nums = [10, 20, 30, 40]
print("stats([10,20,30,40]) =", [Link](nums))
if __name__ == "__main__":
main()
RPC Program – Components Summary Table
Component Type Used in Purpose Simple Meaning
Provides RPC server Enables remote
[Link] Package Server
tools function execution
SimpleXMLRPCServer Class Server Creates RPC server Listens for remote calls
SimpleXMLRPCReque Controls how requests
Class Server Handles RPC requests
stHandler are received
Improves security &
rpc_paths Variable Server Restricts URL path
clarity
Registers remote Makes functions
register_function() Function Server
functions callable remotely
register_introspection_f Enables method Allows clients to see
Function Server
unctions() discovery available functions
Remote arithmetic
add() Function Server Adds two numbers
function
multiply() Function Server Multiplies numbers Remote math operation
Remote string
reverse_text() Function Server Reverses string
operation
stats() Function Server Calculates statistics Remote data processing
Contd..
Waits for client
serve_forever() Function Server Runs the server
calls
Connects to RPC
[Link] Package Client RPC client tools
server
Creates remote Represents remote
ServerProxy Class Client
object server
[Link] Lists server Shows what can be
Function Client
() methods called
Looks local but
[Link]() Function Client Calls remote add()
runs remotely
Calls remote Remote function
[Link]() Function Client
multiply() call
proxy.reverse_text( Calls Remote text
Function Client
) reverse_text() processing
Remote data
[Link]() Function Client Calls stats()
analysis
Thanks & Cheers!!
Small aim is a crime; have great aim.
Bharat-Ratan A. P. J. Abdul Kalam