0% found this document useful (0 votes)
4 views

socket programming

The document contains a Python implementation of a simple calculator server and client using sockets. The server performs basic arithmetic operations (add, subtract, multiply, divide) based on client requests and handles errors such as invalid operations and division by zero. The client connects to the server, sends requests in a specified format, and displays the server's responses.

Uploaded by

sweta.23bce11754
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

socket programming

The document contains a Python implementation of a simple calculator server and client using sockets. The server performs basic arithmetic operations (add, subtract, multiply, divide) based on client requests and handles errors such as invalid operations and division by zero. The client connects to the server, sends requests in a specified format, and displays the server's responses.

Uploaded by

sweta.23bce11754
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import socket

def calculator(operation, num1, num2):


"""
Perform the requested calculation.
:param operation: The operation to perform (add, subtract, multiply, divide).
:param num1: First operand (as string, will be converted to float).
:param num2: Second operand (as string, will be converted to float).
:return: Result of the computation or error message as a string.
"""
try:
num1, num2 = float(num1), float(num2)
if operation == "add":
return f"The result is: {num1 + num2}"
elif operation == "subtract":
return f"The result is: {num1 - num2}"
elif operation == "multiply":
return f"The result is: {num1 * num2}"
elif operation == "divide":
if num2 != 0:
return f"The result is: {num1 / num2}"
else:
return "Error: Division by zero is not allowed."
else:
return "Error: Invalid operation. Use add, subtract, multiply, or
divide."
except ValueError:
return "Error: Invalid numbers. Please provide numeric values."

def start_server():
"""
Start the server and handle client connections.
"""
host = '127.0.0.1' # Localhost
port = 65432 # Port to listen on

# Step 1: Create a TCP/IP socket


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port)) # Step 2: Bind to the specified address and
port
server_socket.listen(1) # Step 3: Listen for incoming connections
print(f"Server started at {host}:{port}")

# Step 4: Accept a client connection


conn, addr = server_socket.accept()
print(f"Connection established with {addr}")

while True:
# Step 5: Receive data from the client
data = conn.recv(1024).decode()
if not data or data.lower() == "exit": # Check if the client wants to
disconnect
print("Client disconnected.")
break

print(f"Received from client: {data}")


parts = data.split()

# Step 6: Process the request


if len(parts) == 3:
operation, num1, num2 = parts
response = calculator(operation, num1, num2)
else:
response = "Error: Invalid format. Use 'operation num1 num2'."

# Step 7: Send the result back to the client


conn.send(response.encode())

conn.close() # Step 8: Close the connection


server_socket.close()

if __name__ == "__main__":
start_server()

client.py-------------------------------------------------------
import socket

def start_client():
"""
Connect to the server and send computation requests.
"""
host = '127.0.0.1' # Server IP
port = 65432 # Server port

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


client_socket.connect((host, port)) # Step 1: Connect to the server
print(f"Connected to server at {host}:{port}")
print("Enter your request in the format: operation num1 num2 (e.g., add 4 5)")
print("Type 'exit' to disconnect.")

while True:
# Step 2: Get user input
message = input("Your request: ")
client_socket.send(message.encode()) # Step 3: Send request to the server

if message.lower() == "exit": # Check if the user wants to disconnect


print("Disconnected from server.")
break

# Step 4: Receive and display the server's response


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

client_socket.close() # Step 5: Close the connection

if __name__ == "__main__":
start_client()

You might also like