In: Computer Science
Write and test a python program to demonstrate TCP server and client connections. The client sends a Message containing the 10 float numbers (FloatNumber[]) , and then server replies with a message containing maximum, minimum, and average of these numbers.
Server.py
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
# Recieve data from client.
data = conn.recv(4096)
# Decode the data.
data_decoded = data.decode("utf-8")
array_strings = data_decoded.split(" ")
# Convert the recieved data to float array.
array = [float(i) for i in array_strings]
# Find max, min, average of data.
max_number = max(array)
min_number = min(array)
average = (sum(array))/(len(array))
# Convert result into string and encode it into bytes to send to client.
result = "Max : " + str(max_number) + " Min: " + str(min_number) + " Average: " + str(average)
result_encoded = result.encode()
# Send encoded result to client.
conn.sendall(result_encoded)
Client.py
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
print("Enter 10 float numbers")
array = [x for x in input().split()]
# Convert the FloatNumber[] to string, encode it and sent it to server.
array_string = " ".join(array)
array_encoded = array_string.encode()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# Connect to server.
s.connect((HOST, PORT))
# Send data to server.
s.sendall(array_encoded)
# Receive data from server.
data = s.recv(4096)
print(data.decode())
Output -
Start both server and client in two separate terminals.
I have added comments for your understanding
I would love to resolve any queries in the comments. Please consider dropping an upvote to help out a struggling college kid :)
Happy Coding !!