This repository has been archived by the owner on Apr 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
301 lines (248 loc) · 9.39 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import json
import model as model
import socket
import threading
BUFFER_SIZE = 1024
COMMANDS = ['join', 'leave', 'register', 'all', 'msg', '?', 'error', 'ch']
WELCOME_MSG = "Connection to the Message Board Server is successful!"
LEAVE_MSG = "Connection closed. Thank you!"
HELP = '''
List of commands:\n
/join <server_ip_address> <port> \n
/leave \n
/register <handle> \n
/all <message> \n
/msg <handle> <message> \n
/?
'''
UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
udp_host = None
udp_port = None
curr_cmd = None
gui = None
connected = False
sending_msg = None
cur_handle = None
def parse_message(message):
"""Parses the message to JSON for reading for the server
Args:
message str: The message of the client to be parsed
Returns:
JSON: Contains a command field, and a message field and/or handle field.
err: Output message to be posted into GUI if there is.
"""
err = None
global udp_host
global udp_port
global curr_cmd
# Splits the string based on parameters
msg = message[1:].split(" ")
msg_dict = {'command':'None'}
if msg[0] == COMMANDS[0] and len(msg) == 3 and udp_host == None:
# /join <server_ip_add> <port>
msg_dict['command'] = 'join'
udp_host = msg[1]
try:
udp_port = int(msg[2])
except:
udp_host = None
udp_port = None
err = get_error(0)
curr_cmd = COMMANDS[0]
elif msg[0] == COMMANDS[1] and len(msg) == 1 and udp_host != None:
# /leave
msg_dict['command'] = 'leave'
curr_cmd = COMMANDS[1]
elif msg[0] == COMMANDS[2] and len(msg) == 2 and udp_host != None and cur_handle == None:
# /register <handle>
msg_dict['command'] = 'register'
msg_dict['handle'] = msg[1]
curr_cmd = COMMANDS[2]
elif msg[0] == COMMANDS[3] and len(msg) >= 2 and udp_host != None:
# /all <messsage>
msg_dict['command'] = 'all'
msg_dict['message'] = ' '.join(msg[1:])
curr_cmd = COMMANDS[3]
elif msg[0] == COMMANDS[4] and len(msg) >= 3 and udp_host != None:
# /msg <handle> <message>
msg_dict['command'] = 'msg'
msg_dict['handle'] = msg[1]
msg_dict['message'] = ' '.join(msg[2:])
curr_cmd = COMMANDS[4]
elif msg[0] == COMMANDS[5] and len(msg) == 1:
# /?
err = HELP
elif msg[0] not in COMMANDS:
err = get_error(4)
elif msg[0] == COMMANDS[0] and udp_host != None:
err = get_error(1)
elif msg[0] == COMMANDS[1] and udp_host == None:
err = get_error(2)
elif msg[0] in COMMANDS[2:] and udp_host == None:
err = get_error(3)
elif msg[0] == COMMANDS[2] and cur_handle != None:
err = get_error(6)
else:
err = get_error(5)
msg_json = json.dumps(msg_dict)
return (msg_json, err)
def handle_adder(message):
if message['command'] == COMMANDS[3]:
# /all
if message['handle'] != None:
return "{handle}: {msg}".format(handle=message['handle'], msg=message['message'])
else:
return message['message']
elif message['command'] == COMMANDS[4]:
# /msg
return "[From {handle}]: {msg}".format(handle=message['handle'], msg=message['message'])
def connect_server(bytesToSend, serverAddressPort):
global connected
global udp_host
global udp_port
if not connected:
try:
UDPClientSocket.settimeout(5)
UDPClientSocket.sendto(bytesToSend, serverAddressPort)
print("Sending to a server...")
message, _ = UDPClientSocket.recvfrom(BUFFER_SIZE)
connected = True
print("RECEIVED SERVER CONNECTION")
decoded_msg = json.loads(message.decode())
print(decoded_msg)
print("\n")
UDPClientSocket.settimeout(None)
if decoded_msg['command'] == COMMANDS[0]:
gui.post(WELCOME_MSG, 'join')
else:
gui.post("Error: Unexpected incorrect receive upon joining.", 'error')
except Exception as e:
print("Timeout on connecting raised and caught.")
print(e)
gui.post("Error: Connection to the Message Board Server has failed! Please check IP Address and Port Number.", 'error')
udp_host = None
udp_port = None
# UDPClientSocket.close()
else:
gui.post("Error: Already connected to {host}:{port}".format(host=udp_host, port=udp_port), 'error')
def send_server(message):
msg, err = parse_message(message)
global connected
global udp_host
global udp_port
global curr_cmd
global gui
global sending_msg
if err == None:
serverAddressPort = (udp_host, udp_port)
bytesToSend = str.encode(msg)
print("UDP Target IP:", udp_host)
print("UDP Target port:", udp_port)
if curr_cmd == COMMANDS[0]:
connect_server(bytesToSend, serverAddressPort)
else:
try:
UDPClientSocket.settimeout(5)
UDPClientSocket.sendto(bytesToSend, serverAddressPort)
UDPClientSocket.settimeout(None)
if curr_cmd == COMMANDS[4]:
print('I am sending out a message.')
# /msg
msg_dict = json.loads(msg)
sending_msg = "[To {handle}]: {msg}".format(handle=msg_dict['handle'], msg=msg_dict['message']);
print(sending_msg)
except Exception as e:
print("Timeout raised and caught.")
print(e)
if curr_cmd == COMMANDS[0]:
gui.post("Error: Connection to the Message Board Server has failed! Please check IP Address and Port Number.", 'error')
elif curr_cmd == COMMANDS[1]:
gui.post("Error: Disconnection failed. Please connect to the server first.", 'error')
else:
gui.post("Error: Unknown error.", 'error')
UDPClientSocket.close()
else:
gui.post(err, 'error')
def get_error(code):
"""Gets the error message based on code
Args:
code (int): Code number to get the error
Returns:
str: Error message to be posted
"""
error = "Error: "
if code == 1:
global udp_host
global udp_port
return error+"Already connected to {host}:{port}".format(host=udp_host, port=udp_port)
elif code == 2:
return error+"Disconnection failed. Please connect to the server first."
elif code == 3:
return error+"You need to connect to a server first."
elif code == 4:
return error+"Command not found."
elif code == 5:
return error+"Command parameters do not match or is not allowed."
elif code == 6:
return error+"You already have a registered handle."
def get_handle() -> str:
global cur_handle
return cur_handle
def get_host() -> str:
global udp_host
return udp_host
def get_port() -> int:
global udp_port
return udp_port
def set_host(host): udp_host = host
def set_port(port): udp_port = port
def set_gui(g) :
global gui
gui= g
def receiver():
global udp_host
global udp_port
global curr_cmd
global gui
global sending_msg
global cur_handle
global connected
while True:
try:
if connected:
message, _ = UDPClientSocket.recvfrom(BUFFER_SIZE)
print("RECEIVED SERVER")
decoded_msg = json.loads(message.decode())
print(decoded_msg)
print("\n")
if decoded_msg['command'] == COMMANDS[1] and curr_cmd == COMMANDS[1]:
udp_host = None
udp_port = None
gui.post(LEAVE_MSG, 'leave')
cur_handle = None
connected = False
elif decoded_msg['command'] == COMMANDS[2] and curr_cmd == COMMANDS[2]:
handle_msg = "Welcome "+str(decoded_msg['handle'])+"!"
gui.post(handle_msg, 'register')
cur_handle = decoded_msg['handle']
# If command is ALL / MSG / ? / error
elif decoded_msg['command'] == COMMANDS[3]:
gui.post(decoded_msg['message'], 'all')
elif decoded_msg['command'] == COMMANDS[4]:
if sending_msg != None:
gui.post(sending_msg, 'msg')
sending_msg = None
if decoded_msg['handle'] != cur_handle:
rcv_msg = "[From {handle}]: {message}".format(handle=str(decoded_msg['handle']), message=str(decoded_msg['message']))
gui.post(rcv_msg, 'msg')
elif decoded_msg['command'] == COMMANDS[6]:
print("Error received from server!")
gui.post(decoded_msg['message'], 'error')
except Exception as e:
# This will spam if you print exceptions.
if e != WindowsError.winerror:
pass
#print(e)
# Separate thread for receiving from server
t1 = threading.Thread(target=receiver)
t1.start()