Uploaded by Prem

Client server echo system

advertisement
Ex No: 1(C)
Date:
CLIENT SERVER SYSTEM
AIM:
To build a simple client-server system. The system you are developing is a simple key-value
store. The client takes user input to get/put/delete keys and passes these requests over the
server. The server maintains a data structure of key-value pairs in memory and returns a suitable
reply to the server. When the request from the client is of the form "put key value", the server
must store the key-value pair in its data structures, provided the key does not already exist. Put
requests on an exis ng key must return an error message. When the client sends a request of
the form "get key value", the value stored against the key must be returned. If the key is not
found, a suitable error message must be returned. The client should be able to issue a delete
request (on an exis ng key) as follows: "del key". For all requests that succeed, the server must
either return the value (in case of get), or the string "OK" (in case of put/del). You may assume
that all keys and values are integers. When the user inputs "Bye", the server should reply
"Goodbye" and close the client connec on. Upon receiving this message from the server, your
client program terminates
ALGORITHM:
SERVER:
STEP 1:Set Up Socket: Create a socket object for communication.
STEP 2:Define Key-Value Store: Initialize an empty dictionary to store key-value pairs.
STEP 3:Handle Client Connection: Define a function to handle client connections.
STEP 4:Accept Connections: Start listening for incoming connections.
STEP 5:Receive Data: Receive data from the client in chunks of 1024 bytes.
STEP 6:Parse Command: Split received data to extract the command and its arguments.
STEP 7:Execute Command: Based on the command, perform appropriate actions:
7.1: For "put": Store key-value pair if the key doesn't already exist.
7.2: For "get": Retrieve value associated with the key if it exists.
7.3: For "del": Delete key-value pair if the key exists.
7.4: For "Bye": Close connection and break loop.
STEP 8:Otherwise, send an error message for invalid commands.
STEP 9:Send Response: Send appropriate responses back to the client.
STEP 10:Close Connection: Close the connection with the client after handling requests.
STEP 11: Continue listening for new connections and repeat the process.
CLIENT:
STEP 1:Import the socket module for networking functionality.
STEP 2:Define a function named communicate_with_server() to handle communication
with the server.
STEP 3:Create a socket object using socket.socket() with AF_INET for IPv4 and
SOCK_STREAM for TCP connection.
STEP 4:Connect the socket to the server address and port using s.connect().
STEP 5:Enter a loop to continually prompt the user for commands.
STEP 6:Send the command entered by the user to the server using s.sendall().
STEP 7:If the command is "Bye", receive a response from the server, print it, and break
the loop; otherwise, receive data from the server and print it.
SERVER SOURCE CODE:
import socket
key_value_store = {}
def handle_client(conn, addr):
print(f"Connected by {addr}")
while True:
data = conn.recv(1024).decode()
if not data:
break
command, *rest = data.split()
if command == "put":
if len(rest) != 2:
conn.sendall(b"Error: Invalid put command format")
else:
key, value = rest
if key in key_value_store:
conn.sendall(b"Error: Key already exists")
else:
key_value_store[key] = value
conn.sendall(b"OK")
elif command == "get":
if len(rest) != 1:
conn.sendall(b"Error: Invalid get command format")
else:
key = rest[0]
if key in key_value_store:
conn.sendall(key_value_store[key].encode())
else:
conn.sendall(b"Error: Key not found")
elif command == "del":
if len(rest) != 1:
conn.sendall(b"Error: Invalid delete command format")
else:
key = rest[0]
if key in key_value_store:
del key_value_store[key]
conn.sendall(b"OK")
else:
conn.sendall(b"Error: Key not found")
elif command == "Bye":
conn.sendall(b"Goodbye")
break
else:
conn.sendall(b"Error: Invalid command")
print(f"Disconnected from {addr}")
conn.close()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("localhost",8989))
s.listen()
print("Server is listening...")
while True:
conn, addr = s.accept()
handle_client(conn, addr)
CLIENT SOURCE CODE:
import socket
def communicate_with_server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(("localhost",8989))
print("Connected to server.")
while True:
command = input("Enter command (put/get/del key value): ").strip()
s.sendall(command.encode())
if command == "Bye":
response = s.recv(1024).decode()
print(response)
break
data = s.recv(1024).decode()
print(data)
if __name__ == "__main__":
communicate_with_server()
OUTPUT:
SERVER:
Server is listening...
Connected by ('127.0.0.1', 54052)
Disconnected from ('127.0.0.1', 54052)
CLIENT:
Connected to server.
Enter command (put/get/del key value): put name prem
OK
Enter command (put/get/del key value): put age 20
OK
Enter command (put/get/del key value): get name
prem
Enter command (put/get/del key value): get age
20
Enter command (put/get/del key value): del age
OK
Enter command (put/get/del key value): get age
Error: Key not found
Enter command (put/get/del key value): del name
OK
Enter command (put/get/del key value): Bye
Goodbye
RESULT:
Thus, the above python program to perform a simple key-value store was executed and the
output verified successfully.
Download