Client Lab4
Client Lab4
This document contains the steps for basic UDP and TCP Client-Server communication along
with additional labs for UDP pinger and multi-threaded TCP server. The activities include
programming tasks to demonstrate connectionless communication, reliable data transfer, round
trip time measurement, and concurrency in networking.
import socket
# UDP Client
server_address = ('localhost', 12345) # Server address
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP socket
while True:
message = input("Enter message to send: ") # User input
if message.lower() == 'exit': # Exit condition
break
sock.sendto(message.encode(), server_address) # Send message
data, _ = sock.recvfrom(4096) # Receive server response
print(f"Received from server: {data.decode()}")
sock.close()
import socket
# UDP Server
server_address = ('localhost', 12345)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP socket
sock.bind(server_address)
while True:
data, client_address = sock.recvfrom(4096) # Receive message
if data:
modified_message = data.decode().upper() # Convert to uppercase
sock.sendto(modified_message.encode(), client_address) # Send response
import socket
# TCP Client
server_address = ('localhost', 12345)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP socket
import socket
# TCP Server
server_address = ('localhost', 12345)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP socket
sock.bind(server_address)
sock.listen(1)
connection.close()
Objective: Students how to measure Round Trip Time (RTT) and handle packet loss using UDP.
Activity Steps:
1. The client sends 10 ping messages to the server.
2. The server responds with pong messages.
3. The client calculates RTT and prints the response time for each ping.
4. If a packet is lost, the client prints a timeout message.
Learning Outcome: Understanding reliability issues in UDP and handling packet loss.
import socket
import time
for i in range(10):
message = f"Ping {i+1}"
start_time = time.time() # Record start time
sock.sendto(message.encode(), server_address) # Send ping message
try:
data, _ = sock.recvfrom(4096) # Receive pong response
round_trip_time = time.time() - start_time # Calculate RTT
print(f"Received {data.decode()} - RTT: {round_trip_time:.4f} seconds")
except socket.timeout:
print(f"Ping {i+1} - Timeout (packet lost)")
sock.close()
import socket
while True:
data, client_address = sock.recvfrom(4096) # Receive ping
if data:
sock.sendto(f"Pong: {data.decode()}".encode(), client_address) # Send pong
import socket
import threading
while True:
client_socket, client_address = server_socket.accept() # Accept client connection
client_handler = threading.Thread(target=handle_client, args=(client_socket, client_address))
client_handler.start() # Handle each client in a new thread