Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Lab 2 & 3

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()

TCP Client Example:

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

UDP Server Example:

import socket

# Create a UDP socket


server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to the port
server_address = ('localhost', 12345)
server_socket.bind(server_address)
while True:
print('Waiting for a message...')
data, client_address = server_socket.recvfrom(1024)
print('Received message:', data.decode())
# Echo the message back to the client
server_socket.sendto(data, client_address)

UDP Client Example:

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)

# Bind the socket to the address and port


server_address = ('localhost', 12345)
server_socket.bind(server_address)

# Listen for incoming connections


server_socket.listen(5)
print("Server is listening for incoming connections...")

# Main loop to accept incoming connections


while True:
client_socket, client_address = server_socket.accept()
# Create a new thread to handle the client
client_thread = threading.Thread(target=handle_client,
args=(client_socket, client_address))
client_thread.start()
Client
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 to the server
message = "Hello, server!"
print(f"Sending: {message}")
client_socket.sendall(message.encode())
# Receive response from the server
data = client_socket.recv(1024)
print("Received:", data.decode())
finally:
# Clean up the connection
client_socket.close()

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

# Create a TCP/IP socket


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the address and port


server_address = ('localhost', 12345)
server_socket.bind(server_address)

# Listen for incoming connections


server_socket.listen(5)
print("Server is listening for incoming connections...")
while True:
# Wait for a connection
print("Waiting for a connection...")
connection, client_address = server_socket.accept()
try:
print("Connection established with", client_address)
while True:
# Receive data from the client
data = connection.recv(1024)
if data:
print("Received:", data.decode())
# Echo back the received data
connection.sendall(data)
else:
print("No more data from", client_address)
break
finally:
# Clean up the connection
connection.close()
Client:
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 to the server
message = "Hello, server!"
print("Sending:", message)
client_socket.sendall(message.encode())

# Receive response from the server


data = client_socket.recv(1024)
print("Received:", data.decode())

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

# Function to handle client connections


def handle_client(client_socket, client_address):
print(f"Accepted connection from {client_address}")
while True:
try:
# Receive data from the client
data = client_socket.recv(1024)
if not data:
break
# Convert received data to integer
num = int(data.decode())

# Perform some computation (e.g., double the number)


result = num * 2

# Send the result back to the client


client_socket.sendall(str(result).encode())
print(f"Sent result to {client_address}: {result}")

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}")

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)

# Bind the socket to the address and port


server_address = ('localhost', 12345)
server_socket.bind(server_address)

# Listen for incoming connections


server_socket.listen(5)
print("Server is listening for incoming connections...")
# Main loop to accept incoming connections
while True:
client_socket, client_address = server_socket.accept()
# Create a new thread to handle the client
handle_client(client_socket, client_address)
Client:
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 to the server
message = input("Enter a number to send to the server: ")
client_socket.sendall(message.encode())

# Receive response from the server


result = client_socket.recv(1024)
print("Received result from server:", result.decode())

finally:
# Clean up the connection
client_socket.close()

You might also like