0% found this document useful (0 votes)
4 views4 pages

Python Socket Server-Client Functions

The document contains server-side and client-side Python code for a TCP/IP application that allows clients to request two functions: counting words and letters in a string, and performing a mathematical operation using a cosine function. The server listens for client connections, processes requests, and sends back results, while the client prompts the user for input and displays the server's response. Additionally, there are placeholders for two functions, Function A and Function B, which log their results to text files based on user input.

Uploaded by

messialhsuni
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views4 pages

Python Socket Server-Client Functions

The document contains server-side and client-side Python code for a TCP/IP application that allows clients to request two functions: counting words and letters in a string, and performing a mathematical operation using a cosine function. The server listens for client connections, processes requests, and sends back results, while the client prompts the user for input and displays the server's response. Additionally, there are placeholders for two functions, Function A and Function B, which log their results to text files based on user input.

Uploaded by

messialhsuni
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Server-side code:

```python
import socket
import random

# Function A
def count_word_letter(input_string):
word_count = len(input_string.split())
letter_count = len(input_string)
word_freq = {}
letter_freq = {}
for word in input_string.split():
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
for letter in input_string:
if letter in letter_freq:
letter_freq[letter] += 1
else:
letter_freq[letter] = 1
most_common_word = max(word_freq, key=word_freq.get)
most_common_letter = max(letter_freq, key=letter_freq.get)
return (word_count, letter_count, most_common_word, most_common_letter)

# Function B
def math_function(input_number):
r = [Link](1, 10)
result = r * [Link](input_number)
return result

# Create a TCP/IP socket


server_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to a specific IP address and port


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

# Listen for incoming connections


server_socket.listen(1)

while True:
# Wait for a connection
print('Waiting for a connection...')
client_socket, client_address = server_socket.accept()
print('Client connected:', client_address)

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

# If no data is received, break the loop


if not data:
break

# Convert the data to a string and split it into function name and
argument
input_str = [Link]('utf-8')
input_list = input_str.split(',')
function_name = input_list[0]
argument = input_list[1]

# Call the appropriate function based on the function name


if function_name == 'count_word_letter':
result = count_word_letter(argument)
response = str(result[0]) + ',' + str(result[1]) + ',' + result[2]
+ ',' + result[3]
elif function_name == 'math_function':
result = math_function(float(argument))
response = str(result)
else:
response = 'Invalid function name'

# Send the response back to the client


client_socket.sendall([Link]('utf-8'))

finally:
# Close the connection
client_socket.close()
print('Client disconnected:', client_address)
```

Client-side code:

```python
import socket

# Create a TCP/IP socket


client_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the server's IP address and port


server_address = ('localhost', 5000)
client_socket.connect(server_address)

try:
while True:
# Get the function name and argument from the user
function_name = input('Enter function name (count_word_letter or
math_function): ')
argument = input('Enter argument: ')

# Combine the function name and argument into a string and send it to the
server
input_str = function_name + ',' + argument
client_socket.sendall(input_str.encode('utf-8'))

# Receive the response from the server and print it


response = client_socket.recv(1024).decode('utf-8')
print('Response:', response)

except KeyboardInterrupt:
# Close the connection on Ctrl+C
print('Closing connection...')
client_socket.close()
```
```python
import socket

# Create a TCP/IP socket


client_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the server's IP address and port


server_address = ('localhost', 5000)
client_socket.connect(server_address)

try:
while True:
# Ask the user to choose a function
print('Choose a function:')
print('1. Count words and letters')
print('2. Mathematical function')
choice = input('Enter your choice (1 or 2): ')

# Get the argument from the user


argument = input('Enter argument: ')

# Send the function name and argument to the server


if choice == '1':
function_name = 'count_word_letter'
elif choice == '2':
function_name = 'math_function'
else:
print('Invalid choice')
continue

input_str = function_name + ',' + argument


client_socket.sendall(input_str.encode('utf-8'))

# Receive the response from the server and print it


response = client_socket.recv(1024).decode('utf-8')
if function_name == 'count_word_letter':
response_list = [Link](',')
print('Word count:', response_list[0])
print('Letter count:', response_list[1])
print('Most common word:', response_list[2])
print('Most common letter:', response_list[3])
elif function_name == 'math_function':
print('Result:', response)

except KeyboardInterrupt:
# Close the connection on Ctrl+C
print('Closing connection...')
client_socket.close()
```
def FunctionA():
# Implement Function A here
return "Function A result"

def FunctionB():
# Implement Function B here
return "Function B result"

# Create empty files for Function A and B results


with open("FunctionA_results.txt", "w") as f:
pass

with open("FunctionB_results.txt", "w") as f:


pass

while True:
# Prompt the user to continue or stop
user_input = input("Press 'y' to continue or 'n' to stop: ")

# Exit the loop if the user chooses to stop


if user_input.lower() == "n":
break

# Call Function A and store result in FunctionA_results.txt


function_a_result = FunctionA()
with open("FunctionA_results.txt", "a") as f:
[Link](f"{[Link]()} - {function_a_result}\n")

# Call Function B and store result in FunctionB_results.txt


function_b_result = FunctionB()
with open("FunctionB_results.txt", "a") as f:
[Link](f"{[Link]()} - {function_b_result}\n")
```

You might also like