Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
import socket
# Constants
ADDR = "localhost"
PORT = 50009
# Enable print logging for debugging
_LOGGING = False
def printLog(message: str) -> None:
"""Print the message if logging is enabled
:param message: The message to print
:type message: str
"""
if _LOGGING:
print(message)
def run_client():
printLog(f"Attempting connection to {ADDR} on port {PORT}")
try:
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect((ADDR, PORT))
except socket.error as e:
print(f"Socket Error: {e}")
return
printLog(f"Successfully connected to {ADDR} on port {PORT}")
while True:
query = input("Input query: ")
try:
# Status code 200 indicates a query
encodedQuery = f"200:{query}:END".encode()
break
except UnicodeEncodeError:
print("Data is not in unicode format")
# Collect input until the data is in unicode format
continue
clientSocket.send(encodedQuery)
printLog(f"Query sent: {query}")
encodedData = b""
while True:
# Receive data in chunks of 1024 bytes
encodedDataChunk = clientSocket.recv(1024)
if not encodedDataChunk:
break
encodedData += encodedDataChunk
# Check if the data received is incomplete
if len(encodedDataChunk) < 1024 and encodedDataChunk[-3:] != b"END":
print("Data received is incomplete, exiting...")
return
# Data send is complete once the END tag is received
if encodedDataChunk[-3:] == b"END":
break
try:
data = encodedData.decode()
except UnicodeDecodeError:
print("Data received is not in unicode format, exiting...")
clientSocket.close()
return
# Check if the server sent an error message (status code 4##)
if data.startswith("4"):
print(f"Server Response {data.split(":")[0]}: {data.split(':')[1]}")
clientSocket.close()
return
# Check if the server sent an unexpected response (successful is status code 1##)
elif not data.startswith("1"):
print(f"Unexpected response: {data}")
clientSocket.close()
return
# Extract the response from in between the Status Code and END tags
wordsList = data.split(":")[2]
wordCount = data.split(":")[1]
try:
wordCount = int(wordCount)
except ValueError:
print("Response is not in the expected format, exiting...")
clientSocket.close()
return
if not wordCount:
print("No matching words found")
clientSocket.close()
return
# Extract the words from the response (comma-separated)
words = wordsList.split(",")
# Print the matching words, add an 's' to "word" if there is more than one word
print(f"Found {wordCount} matching word{'s' if wordCount > 1 else ''}:")
for word in words:
print(word)
clientSocket.close()
return
if __name__ == "__main__":
run_client()