Lab2 Socket Programming
Lab2 Socket Programming
These examples demonstrate how to create TCP and UDP servers and clients in Python using
the socket module, which interacts with the TCP/IP protocol stack to enable communication
over networks.
Example 1
TCP Server Example:
import socket
# Create a TCP/IP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 12345)
server_socket.bind(server_address)
# Listen for incoming connections
server_socket.listen(5)
while True:
print('Waiting for a connection...')
connection, client_address = server_socket.accept()
try:
print('Connection from', client_address)
while True:
data = connection.recv(1024)
if data:
print('Received:', data.decode())
connection.sendall(b'Received: ' + data)
else:
print('No more data from', client_address)
break
finally:
connection.close()
import socket
# Create a TCP/IP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the server
server_address = ('localhost', 12345)
client_socket.connect(server_address)
try:
# Send data
message = 'Hello, server!'
print('Sending:', message)
client_socket.sendall(message.encode())
# Receive response
data = client_socket.recv(1024)
print('Received:', data.decode())
finally:
# Clean up the connection
client_socket.close()
Example 2
import socket
import socket
# Create a UDP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Send data
message = 'Hello, server!'
print('Sending:', message)
client_socket.sendto(message.encode(), ('localhost', 12345))
# Receive response
data, server_address = client_socket.recvfrom(1024)
print('Received:', data.decode())
# Clean up the connection
client_socket.close()
Example 3
TCP Server with Threading Example: This example demonstrates a TCP
server that can handle multiple client connections concurrently using threading.
In this example, the server listens for incoming connections and spawns a new
thread to handle each client connection. This allows the server to handle multiple
clients simultaneously without blocking. The client connects to the server, sends
a message, and receives a response from the server.
Server :
import socket
import threading
# Function to handle client connections
def handle_client(client_socket, client_address):
print(f"Accepted connection from {client_address}")
while True:
data = client_socket.recv(1024)
if not data:
break
print(f"Received data from {client_address}: {data.decode()}")
client_socket.sendall(b"Server received: " + data)
print(f"Connection with {client_address} closed.")
client_socket.close()
# Create a TCP/IP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Example 4
Echo Server Example: In this example, the server receives a message from the
client and echoes it back.
In this example, the server listens for incoming connections and, upon
connection, receives data from the client, echoes it back, and sends it back to the
client. The client connects to the server, sends a message, receives the echoed
message from the server, and prints it. This demonstrates the basic TCP client-
server communication using Python's socket module.
Server:
import socket
try:
# Send data to the server
message = "Hello, server!"
print("Sending:", message)
client_socket.sendall(message.encode())
finally:
# Clean up the connection
client_socket.close()
Example 5
In this example, the server receives numerical data from the client, performs a
simple calculation, and sends the result back to the client.
In this example, the server listens for incoming connections and spawns a new
thread to handle each client connection. The client connects to the server and
sends a numerical value. The server receives the value, performs a calculation
(doubling the number), and sends the result back to the client. If the client sends
non-numeric data, the server handles the error and sends an appropriate error
message back to the client.
Server :
import socket
except ValueError:
# Handle non-integer input from the client
error_message = "Invalid input. Please send a valid integer."
client_socket.sendall(error_message.encode())
print(f"Sent error message to {client_address}:
{error_message}")
try:
# Send data to the server
message = input("Enter a number to send to the server: ")
client_socket.sendall(message.encode())
finally:
# Clean up the connection
client_socket.close()