-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
106 lines (85 loc) · 3.23 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#client.py
import socket
import sys
from connection import Connection
from query import Query
from user import User
HOST = '127.0.0.1'
PORT = 65432
MAX_MESSAGE_SIZE = 512
MANUAL = "If you want to write new message, type '!message'\n\
If you want to check your inbox, type '!inbox'\n\
If you want to delete an account (admin only), type '!delete'\n\
If you want to get info about this server, type '!info'\n\
If you need to see this manual again, type '!help'\n\
If you want to exit, type '!stop'"
class Client:
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connection = Connection(self.socket)
self.user = User()
self.query = Query()
self.start_client(HOST, PORT)
pass
def start_client(self, host, port):
self.socket.connect((host, port))
if not self.user.login_user(self.socket):
header, data = self.connection.receive_data()
self.query.process_query(header, data)
while True:
command = input(f"{self.user.username} >:")
header, message = self.process_user_command(command)
if header == "error_msg":
if isinstance(message, str):
print(message)
else:
pass
else:
header, data = self.connection.receive_data()
self.query.process_query(header, data)
def process_user_command(self, command):
match command:
case "!message":
self.send_message()
return "ack", 1
case "!inbox":
self.connection.send_data("check_inbox", self.user.username)
return "ack", 1
case "!read":
self.connection.send_data("read_message", self.user.username)
return "ack", 1
case "!delete":
uname_to_delete = input("Enter name of the user to be removed from database: ")
remove_user = {
"calling_user": self.user.username,
"deleted_user": uname_to_delete
}
self.connection.send_data("delete", remove_user)
return "ack", 1
case "!help":
print(MANUAL)
return "error_msg", 1
case "!info":
self.connection.send_data("check_info", "")
return "ack", 1
case "!stop":
self.connection.send_data("stop", "")
self.socket.close()
sys.exit()
case _:
error_msg = "Wrong command, try again"
return "error_msg", error_msg
def send_message(self):
receiver = input("Enter received name: ")
message = input("Enter message (up to 255 characters): ")
while len(message) > 255:
print("Message too long, try again")
message = input("Enter message (up to 255 characters): ")
message_dict = {
"sender": self.user.username,
"receiver": receiver,
"message": message,
}
self.connection.send_data("send_message", message_dict)
client = Client()
client.start_client(HOST, PORT)