EXP6

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

EXP6: Programming a Client-Server System Using Python

Introduction

Programming a Client-Server system is fundamental to network communication.


In this setup, one device acts as a Server (service provider) that listens for and
responds to requests, while the other device acts as a Client (request sender) that
sends requests and receives responses. In this lab, we will program a simple Server
and Client using Python, demonstrating how they exchange messages over a local
network.

Required Tools

• Python 3
• The socket library (included with Python)
• The thread library (included with Python)
• An Integrated Development Environment (IDE), such as Visual Studio Code or
PyCharm

Objectives

1. Understand how to set up a Server and a Client for network communication.


2. Learn how to exchange messages over a network using Python’s socket library.
3. Implement multi-message exchange between Client and Server.

[email protected]
Experiment Steps

1. Setting Up the Server


o Import the socket library: This library provides tools to create a network
connection object.
o Define the Server IP address and port : Specify the IP address and port that
the Server will listen on.
o Create a Server Socket.
o Bind the socket to the specified IP and port.
o Listen for incoming connections client requests using listen().
o Accept a connection from the client.
o Receive the client’s message and print it.
o Close the connection after receiving the message.

2. Setting Up the Client

1. Import the socket library.


2. Specify the IP and port of the server to connect to the Server.
3. Create the client socket for the connection.
4. Connect to the server : Use connect() to initiate the connection to the Server.
5. Send a message to the server.
6. Close the connection after sending the message.

[email protected]
Server Code
Save the following code in a file, e.g., server.py:
import socket
# Server settings
server_ip = '127.0.0.1' # Localhost
server_port = 12345 # Arbitrary port, can be changed
# Set up Server Socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((server_ip, server_port))
server_socket.listen(1) # Allow one connection
print(f"Server is listening on {server_ip}:{server_port}...")
# Accept a connection from the client
client_socket, client_address = server_socket.accept()
print(f"Connected to {client_address}")
# Receive a message from the client
message = client_socket.recv(1024).decode() # Receive up to 1024 bytes
print("Received message from Client:", message)
# Close the connection
client_socket.close()
server_socket.close()

[email protected]
[email protected]
Client Code
Save the following code in a file, e.g., client.py:
import socket
# Server connection settings
server_ip = '127.0.0.1'
server_port = 12345
# Set up Client Socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server
client_socket.connect((server_ip, server_port))
print(f"Connected to server at {server_ip}:{server_port}")
# Send a message to the server
message = "Hello from Client!"
client_socket.sendall(message.encode())
print("Message sent to Server:", message)
# Close the connection
client_socket.close()

[email protected]
[email protected]
Server Received Massage

[email protected]
Code for client- server. In the same pc
import socket
import threading
server_ip = '0.0.0.0'
server_port = 6000
def run_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((server_ip, server_port))
server_socket.listen(1)
print(f"Server is listening on {server_ip}:{server_port}...")
client_socket, client_address = server_socket.accept()
print(f"Connected to {client_address}")
message = client_socket.recv(1024).decode()
print(f"Received message from Client: {message}")
client_socket.close()
server_socket.close()
def run_client():
import time
time.sleep(1)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((server_ip, server_port))
print(f"Connected to server at {server_ip}:{server_port}")
message = "Hello from Client on the same machine!"
client_socket.sendall(message.encode())
print(f"Message sent to Server: {message}")
client_socket.close()
server_thread = threading.Thread(target=run_server)
client_thread = threading.Thread(target=run_client)
server_thread.start()
client_thread.start()
server_thread.join()
client_thread.join()

[email protected]
[email protected]
. Observing the Results

• When you run the server, it will display that it is waiting for a connection.
• After running the client, a connection message will appear on the server’s
terminal along with the received message.
• The client terminal will also display a message confirming that the message was
sent to the server.

Code Explanation

• Server:
• Listens for connections on 127.0.0.1:12345.
• Accepts the client connection and receives the message.
• Prints the received message and closes the connection.
• Client:
• Connects to the server at 127.0.0.1:12345.
• Sends a text message.
• Closes the connection after sending the message.

Important Notes

• Make sure to start the server first, then the client.


• Use 127.0.0.1 as the IP address for localhost testing. To try the connection on
a local network, use the actual IP address of the device running the server.
• IP Address: In a local network, replace 127.0.0.1 with the internal IP address of
the Server device.(if you have internet)

[email protected]
Modifying the Server Code to Receive Multiple Messages

In the server code, we’ll add a while loop to allow the server to receive multiple
messages from the client. The loop will end if the server receives a message with a
specific word, such as "exit".

import socket
# IP and port settings
server_ip = '127.0.0.1' # local address
server_port = 12345

# Setting up the server socket


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((server_ip, server_port))
server_socket.listen(1)
print(f"Server is listening on {server_ip}:{server_port}...")

# Accept a connection from the client


client_socket, client_address = server_socket.accept()
print(f"Connected to {client_address}")

# Receive messages from the client in a loop


try:
while True:
# Receive a message from the client
message = client_socket.recv(1024).decode()

# Check if the message is "exit" to end the connection


if message.lower() == "exit":
print("Client has disconnected.")
break

print(f"Received message from Client: {message}")

# Send a response back to the client


response = f"Server received: {message}"
client_socket.sendall(response.encode())

except Exception as e:
print(f"An error occurred: {e}")
# Close the connection
client_socket.close()
server_socket.close()

[email protected]
[email protected]
Modifying the Client Code to Send Multiple Messages
In the client code, we’ll also add a while loop to allow the user to input messages
and send them to the server continuously. The client will keep sending messages
until the user types "exit".

import socket

# Server connection settings


server_ip = '127.0.0.1'
server_port = 12345

# Setting up the client socket


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

# Connect to the server


client_socket.connect((server_ip, server_port))
print(f"Connected to server at {server_ip}:{server_port}")

try:
while True:
# User inputs a message
message = input("Enter message (or 'exit' to quit): ")

# Send the message to the server


client_socket.sendall(message.encode())

# End the connection if the message is "exit"


if message.lower() == "exit":
print("Disconnecting from server.")
break

# Receive a response from the server


response = client_socket.recv(1024).decode()
print(f"Received from Server: {response}")

except Exception as e:
print(f"An error occurred: {e}")
finally:
# Close the client connection
client_socket.close()

[email protected]
[email protected]
Server Received Multiple Messages from client

[email protected]
Modifying to send and receive (client- server) In the same pc

import socket
import threading
import time

# IP and port settings


server_ip = '127.0.0.1' # Local IP address
server_port = 12345

# Function to run the server


def run_server():
# Set up the server socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((server_ip, server_port))
server_socket.listen(1)
print(f"Server is listening on {server_ip}:{server_port}...")

# Accept client connection


client_socket, client_address = server_socket.accept()
print(f"Connected to {client_address}")

# Receive messages from the client in a loop


try:
while True:
# Receive a message from the client
message = client_socket.recv(1024).decode()
if message.lower() == "exit":
print("Client has disconnected.")
break
print(f"Received message from client: {message}")

# Send a response to the client


response = f"Server received: {message}"
client_socket.sendall(response.encode())
except Exception as e:
print(f"Server error occurred: {e}")
finally:
# Close the connections
client_socket.close()
server_socket.close()

# Function to run the client


def run_client():

[email protected]
# Wait a few seconds to ensure the server starts first
time.sleep(1)

# Set up the client socket


client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((server_ip, server_port))
print(f"Connected to server at {server_ip}:{server_port}")

try:
while True:
# Get message input from the user
message = input("Enter message (or 'exit' to disconnect): ")
client_socket.sendall(message.encode())
if message.lower() == "exit":
print("Disconnecting from server.")
break

# Receive response from the server


response = client_socket.recv(1024).decode()
print(f"Response from server: {response}")
except Exception as e:
print(f"Client error occurred: {e}")
finally:
# Close the client connection
client_socket.close()

# Create and run threads for both server and client


server_thread = threading.Thread(target=run_server)
client_thread = threading.Thread(target=run_client)

server_thread.start() # Start the server thread


client_thread.start() # Start the client thread

# Wait for both threads to complete


server_thread.join()
client_thread.join()

[email protected]
[email protected]
Explanation of Modifications

1. In the Server:
• The while loop (while True) allows the server to keep receiving messages from
the client.
• If the server receives the message "exit", it will end the connection.
• The server sends a response back to the client after receiving each message,
confirming its receipt.
2. In the Client:
• Adding a while True loop allows the user to input messages and send them
repeatedly to the server.
• Exiting the loop by typing "exit" will close the connection with the server.
• After sending each message, the client waits for a response from the server and
prints it.

Running the Program

1. Start the server first using the modified server code (server.py).
2. Start the client using the modified client code (client.py).
3. Enter multiple messages in the client window to see how they are received and
processed in the server window.
4. To end the connection, type "exit" in the client window, and both the client and
server will close the connection properly.

[email protected]
GOOD LUCK

[email protected]

You might also like