PYTHON
UNIT IV
Socket programming:
Socket programming in Python allows two networked computers (or processes) to communicate
directly using TCP or UDP sockets. Python provides a built-in module called socket for this purpose.
Key Concepts:
Sockets are endpoints for communication. They can be used for client-server models or peer-
to-peer models.
AF_INET designates IPv4 addressing.
SOCK_STREAM is used for TCP (reliable, connection-oriented).
SOCK_DGRAM is used for UDP (unreliable, connectionless).
The server binds to an IP and port, listens for incoming connections, accepts a client, then
receives and responds with a message.
The client connects to the server and sends/receives data over the socket5.
Key Socket Methods:
socket(): Create a new socket instance.
bind(): Attach the socket to an IP and port (mainly for servers).
listen(): Start waiting for client connections (server).
accept(): Accept a new incoming client connection (server).
connect(): Connect to a remote socket (client).
send()/sendall(): Send data.
recv(): Receive data.
close(): Close the socket.
Example program (SERVER([Link]))
s = [Link]()
import socket
[Link](('localhost', 12345))
[Link](1)
print("Waiting for connection...")
conn, addr = [Link]()
print("Connected by", addr)
msg = [Link](1024)
print("Client says:", [Link]())
[Link](b"Hello client!")
[Link]()
client([Link])
import socket
s = [Link]()
[Link](('localhost', 12345))
[Link](b"Hello server!")
msg = [Link](1024)
print("Server says:", [Link]())
[Link]()
Handling multiple clients :
Here’s the information on handling multiple clients in Python socket programming, organized in
point-wise format:
The most common approaches for handling multiple clients:
o Multi-threaded server (using the threading module)
o Non-blocking/scalable server (using the selectors module)
Multi-Threaded Server:
The main server thread listens for connections.
On each new client connection, a new thread is started to handle communication with that
client.
This allows the server to interact with multiple clients simultaneously.
Example:
o Use the threading module.
o Each client’s communication logic is run in a separate thread.
Non-Blocking Server with Selectors:
For scalability (hundreds or thousands of clients), use non-blocking IO with selectors.
Sockets are set to non-blocking mode.
A [Link] object is used to manage multiple sockets.
An event loop handles incoming/outgoing data for all clients in a single thread (no per-client
threads).
This is more complex but much more efficient for high-load servers.
Group Chat Case:
To create a group chat:
o Maintain a list of client sockets.
o Broadcast received messages from any client to all the others.
Client side scripting :
Client-side scripting in Python means writing scripts that act as the client in a network setup,
connecting to a server to send/receive data.
Key steps involved:
o Import the socket library (built-in to Python).
o Create a socket object using [Link](), usually with AF_INET for IPv4 and
SOCK_STREAM for TCP.
o Connect to the server with connect((hostname, port)).
o Send data using send() or sendall().
o Receive data from the server using recv().
o Close the socket using close() when done.
Example steps in code:
o Define server IP and port.
o Create a socket and connect.
o Send a message to the server.
o Receive the server’s reply.
o Print the response and close the connection.
The client always initiates the connection.
Always run the server code first so the client has somewhere to connect.
The main client workflow is: connect → send request → receive response → disconnect.
For UDP, the basics are similar but you use SOCK_DGRAM, and methods like send to and recv
from.
If you want to connect to other services (like for web scraping), specialized libraries (such as
requests for HTTP) are used.
Server side scripting :
Server-side scripting in Python means creating scripts that act as the server, listening for
incoming connections from clients and handling requests.
Key steps involved:
o Import the socket library (built-in to Python).
o Create a socket object using [Link](), usually with AF_INET for IPv4 and
SOCK_STREAM for TCP.
o Bind the socket to a specific IP address and port using bind((hostname, port)).
o Listen for connections with listen().
o Accept incoming connections with accept(), which returns a new socket object for
communication and the client’s address.
o Receive data from the client using recv().
o Send data or a response back to the client using send() or sendall().
o Close the client connection using close() when done.
o Optionally, loop these steps to handle multiple client connections.
Example steps in code:
o Define server IP and port.
o Create a socket, bind, and listen.
o Accept a connection from a client.
o Receive and send messages as needed.
o Print what was received/sent.
o Close the connections when finished.
The server waits passively for clients to connect.
The server can typically handle one client at a time, unless you use threading, async, or
selectors to handle multiple clients simultaneously.
Always run the server script before the client so the client has somewhere to connect.
The basic workflow: listen → accept connection → receive request → send response → close
connection (repeat as needed).
For UDP, use SOCK_DGRAM, and methods like recvfrom and sendto instead of accept and
connect.
Advanced servers might use threading or asynchronous programming for handling multiple
clients at once.
CGI scripts with user interactions:
Here’s how you can create CGI scripts with user interactions in Python, presented point-wise for
clarity:
CGI (Common Gateway Interface) allows you to create dynamic web pages where Python
scripts interact with users via web forms.
Basic Workflow:
o The user fills out an HTML form and submits it.
o The web server invokes your Python CGI script.
o The script reads user input from the form, processes it, and returns a response.
Key Steps to Write a User-Interactive Python CGI Script:
o 1. Import the CGI module:
import cgi
o 2. Print the required HTTP content-type header:
e.g., print("Content-type: text/html\n")
o 3. Access form data submitted by the user:
Create a FieldStorage instance:
form = [Link]()
o 4. Retrieve specific user input:
Use .getvalue() for fields, e.g.:
name = [Link]('name')
o 5. Generate HTML output as the response:
Print HTML with embedded user data or dynamic content.
Example: Simple CGI Script with Form User Input Handling
o HTML Form (frontend):
o When the form is submitted, the script greets the user using their input.
You can handle multiple fields similarly:
o Extract each using [Link]('fieldname').
You can use checkboxes, radio buttons, text areas, etc., in forms and process their data the
same way.
For POST forms:
The usage is the same; only the form’s method changes to "post".
Security Tip:
Always escape or sanitize user inputs when redisplaying them to avoid XSS attacks.
Python script (back end):
#!/usr/bin/python3
import cgi
print("Content-type:text/html\n")
form = [Link]()
name = [Link]('name')
print("<html><head><title>CGI User Interaction</title></head><body>")
if name:
print(f"<h2>Hello, {name}!</h2>")
else:
print("<h2>No name provided.</h2>")
print("</body></html>")
When the form is submitted, the script greets the user using their input
Passing Parameters :
Parameters are variables specified in a function definition; arguments are the actual values
passed to these parameters when calling the function.
Common parameter passing methods in Python:
1. Positional Arguments (Required Arguments):
Arguments are passed in the same order as the parameters are defined.
All required parameters must be provided.
Example:
python
def add(a, b):
return a + b
add(2, 3) # a=2, b=3
2. Keyword Arguments (Named Arguments):
Arguments are passed by explicitly naming the parameters.
Order does not matter.
Example:
python
add(b=3, a=2)
3. Default Arguments:
Parameters can have default values.
If an argument is not provided, the default is used.
Example:
python
def greet(name="World"):
print(f"Hello, {name}!")
greet()
greet("Alice")
4. Variable-Length Arguments:
Use *args to accept any number of positional arguments as a tuple.
Use **kwargs to accept any number of keyword arguments as a dictionary.
Examples:
python
def func(*args):
for arg in args:
print(arg)
func(1, 2, 3)
def func2(**kwargs):
for k, v in [Link]():
print(k, v)
func2(name="Alice", age=25)
Passing parameters by object reference:
o Python’s parameter passing model is often called pass-by-object-reference or call-by-
sharing.
o Mutable objects (like lists, dictionaries) can be modified inside the function, affecting
the original.
o Immutable objects (like integers, strings) cannot be changed inside the function.
o Example:
python
def modify_list(lst):
[Link](4)
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) #Outputs [1, 2, 3, 4]
Functions as parameters:
o Python allows passing functions themselves as arguments to other functions.
o Example:
python
def add(a, b):
return a + b
def operate(func, x, y):
return func(x, y)
print(operate(add, 2, 3)) # Outputs 5
Order rules:
o Positional arguments must come before keyword arguments.
o Default arguments must come after all required parameters.