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
import sys
# 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 handle_query(clientSocket: socket.socket) -> bool:
while True:
query = input("Input query: ")
if query == "quit":
# Exit the connection by sending 201 status code
clientSocket.send("201:Client Disconnecting:END".encode())
printLog("Closing connection with server")
return False
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 False, do not recover from this error
return False
# 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...")
# Do not recover from this error
return False
# 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]}")
# Return True, continue connection even after this error (expected error)
return True
# Check if the server sent an unexpected response (successful is status code 1##)
elif not data.startswith("1"):
print(f"Unexpected response: {data}")
# Do not recover from this error
return False
# 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...")
# Do not recover from this error
return False
if not wordCount:
print("No matching words found")
# Continue Connection
return True
# 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)
# Continue Connection
return True
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 handle_query(clientSocket):
continue
clientSocket.close()
return
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "-debug":
_LOGGING = True
run_client()