-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient.py
More file actions
573 lines (540 loc) · 21 KB
/
client.py
File metadata and controls
573 lines (540 loc) · 21 KB
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# client
import socket
import threading
import time
import sys
print("Welcome to the stock trading application!\n")
# create socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get server address and create address pair
connectCmd = input("Please input a server address and port: ")
address = (connectCmd[0:connectCmd.find(":")],
int(connectCmd[connectCmd.find(":") + 1:]))
connection = False
MSGLEN = 256
# command thread variables
message = ""
oldMessage = ""
listening = False
listenerThread = None
# try to connect to server - error if it fails and prompt again for server address
while connection == False:
try:
s.connect(address)
connection = True
print(
f"Connection successfully established with {address[0]}:{address[1]}\n")
except Exception as e:
print(
f"Connection could not be established with server on {address[0]}:{address[1]} \nException is " + str(e))
connectCmd = input("Please input another server address and port: ")
if connectCmd.lower() == "quit":
break
address = (connectCmd[0:connectCmd.find(":")],
int(connectCmd[connectCmd.find(":") + 1:]))
# sends input string of max length MSGLEN to the server
def sendMsg(msg):
totalSent = 0
while len(msg) < MSGLEN:
msg = msg + " "
while totalSent < MSGLEN:
sent = s.send(msg[totalSent:].encode("utf-8"))
if sent == 0 and msg != "":
quitClient()
break
elif msg == "":
break
totalSent += sent
print("msg '" + msg.strip() + "' sent with total bytes: " + str(totalSent))
# recieves string from server
def recieveMsg():
chunks = []
bytesRecieved = 0
while bytesRecieved < MSGLEN:
chunk = s.recv(min(MSGLEN - bytesRecieved, 2048))
if chunk.decode("utf-8") == "":
quitClient()
break
chunks.append(chunk)
bytesRecieved += len(chunk)
returnStr = ""
for c in chunks:
returnStr = returnStr + c.decode("utf-8")
print("msg '" + returnStr.strip() +
"' recieved with total bytes: " + str(bytesRecieved))
return returnStr.strip()
# client close function
def quitClient():
s.close()
print("Connection broken - Program exiting...\n")
global connection
global listening
connection = False
sys.exit(0)
def isServerClose(sock: socket.socket):
try:
# this will try to read bytes without blocking and also without removing them from buffer (peek only)
sock.setblocking(False)
data = sock.recv(2048, socket.MSG_PEEK)
if data.decode("utf-8") == "":
return True
except BlockingIOError:
sock.setblocking(True)
return False # socket is open and reading from it would block
except ConnectionResetError:
return True # socket was closed for some other reason
except Exception as e:
sock.setblocking(True)
return False
sock.setblocking(True)
return False
# executes command
loggedIn = False
uid = None
userName = None
def executeCMD(cmd: str):
global uid
global userName
# check login
global loggedIn
if loggedIn == False and (cmd.lower() != "quit" and cmd[0:5].lower() != "login"):
print("Command cannot be executed. You are not logged in. \nPlease try the login command or quit the program.")
return
# run command
if cmd.lower() == "shutdown".lower():
sendMsg(cmd)
response = recieveMsg()
if response[0:6] == "200 OK":
print(response[7:])
quitClient()
else:
print(response)
elif cmd.lower() == "quit".lower():
sendMsg("quit")
quitClient()
elif cmd[0:5].lower() == "login".lower():
params = cmd.split(" ")
if (len(params) == 0 or len(params) == 1 or params[1] == ""):
un = input("Please enter a username: ")
password = input("Please enter password: ")
cmd = ("LOGIN " + un + " " + password)
elif (len(params) == 2):
un = params[1]
password = input("Please enter password: ")
cmd = ("LOGIN " + un + " " + password)
sendMsg(cmd)
response = recieveMsg()
if response[0:3] == "200":
loggedIn = True
uid = response[7:8]
userName = cmd.split()[1]
print(response[9:])
elif response[0:3] == "403":
print(response)
elif cmd.lower() == "logout".lower():
sendMsg(cmd)
response = recieveMsg()
uid = None
userName = ""
loggedIn = False
elif cmd.lower()[0:7] == "balance".lower():
sendMsg(cmd)
response = recieveMsg()
if response[0:3] == "200":
print(f"Balance for user {userName}: " + response[7:])
elif response[0:3] == "400":
print(response)
elif cmd.lower()[0:7] == "deposit".lower():
amount_flag = False
params = cmd.split(" ")
if (len(params) == 0 or len(params) == 1 or params[1] == ""):
amount = input("Please enter deposit amount\n")
while (amount_flag == False):
try:
float(amount)
if float(amount) < 0:
raise("negative")
amount_flag = True
except:
amount_flag = False
amount = input("Please enter a positive deposit amount\n")
cmd = "DEPOSIT " + str(amount)
else:
amount = params[1]
while (amount_flag == False):
try:
float(amount)
if float(amount) < 0:
raise("negative")
amount_flag = True
except:
amount_flag = False
amount = input("Please enter a positive deposit amount\n")
cmd = "DEPOSIT " + str(amount)
sendMsg(cmd + " "+str(uid))
response = recieveMsg()
if response[0:3] == "200":
print(f"Updated Balance for user {userName}: " + response[7:])
elif response[0:3] == "400":
print(response)
elif cmd.lower()[0:6] == "lookup".lower():
params = cmd.split(" ")
if (len(params) == 0 or len(params) == 1 or params[1] == ""):
search = input("Please enter stock to lookup\n")
cmd = "LOOKUP " + str(search)
sendMsg(cmd + " " + str(uid))
response = recieveMsg()
if response[0:3] == "200":
print(f"Found stock records matching you search for user {userName}: ")
stocks = response[7:].split()
stocksList = []
for stock in stocks:
stockTuple = stock[1:-1].split(",")
stocksList.append(stockTuple)
for stock in stocksList:
print(stock[0], stock[1], stock[3])
elif response[0:3] == "404":
print(response)
elif cmd.lower()[0:4] == "list".lower():
sendMsg(cmd)
response = recieveMsg()
if response[0:3] == "200":
stocks = response[7:].split()
stocksList = []
for stock in stocks:
stockTuple = stock[1:-1].split(",")
stocksList.append(stockTuple)
if userName == "root":
print("The list of stock records for all users:")
for stock in stocksList:
print(stock[0], stock[1], stock[3], stock[4])
else:
print(f"The list of stock records for user {userName}:")
for stock in stocksList:
print(stock[0], stock[1], stock[3])
elif response[0:3] == "400":
print(response)
elif cmd.lower()[0:3] == "who".lower():
sendMsg(cmd)
response = recieveMsg()
if response[0:3] == "200":
print("The list of active users is: ")
activeUsers = response[6:].split()
for user in activeUsers:
print(user)
else:
print(response)
elif cmd.lower()[0:3] == "buy".lower():
parameters = cmd.split(" ")
price_flag = False # boolean for the price per share
stock_flag = False # boolean for stock amount
symbol = ""
# "BUY" or "BUY " case we need a stock symbol, price per share, stock ammount and a user id
if len(parameters) == 0 or len(parameters) == 1:
symbol = str(input("Please enter stock symbol\n"))
while stock_flag == False:
try:
# Ensure that stock is a positive number
stock = float(
input("Please enter stock ammount as a float or integer\n"))
if stock > 0:
stock_flag = True
except:
stock_flag = False
while price_flag == False:
try:
# Ensure that price is a positive number
price = float(
input("Please enter stock price per share as a float or integer\n"))
if price > 0:
price_flag = True
except:
price_flag = False
cmd = "BUY " + symbol + " " + \
str(stock) + " " + str(price) + " " + \
str(uid)+"\n" # The message to be sent
elif len(parameters) == 2: # "BUY symbol" case
symbol = str(parameters[1])
while stock_flag == False:
try:
stock = float(
input("Please enter stock ammount as a float or integer\n"))
if stock > 0:
stock_flag = True
except:
stock_flag = False
while price_flag == False:
try:
price = float(
input("Please enter stock price per share as a float or integer\n"))
if price > 0:
price_flag = True
except:
price_flag = False
cmd = "BUY " + symbol + " " + \
str(stock) + " " + str(price) + " " + str(uid)+"\n"
elif len(parameters) == 3: # "BUY symbol pricepershare" case
symbol = str(parameters[1])
try:
stock = float(parameters[2])
if stock < 0:
raise("less than 0")
except:
while stock_flag == False:
try:
stock = float(
input("Please enter stock ammount as a float or integer\n"))
if stock > 0:
stock_flag = True
except:
stock_flag = False
while price_flag == False:
try:
price = float(
input("Please enter stock price per share as a float or integer\n"))
if price > 0:
price_flag = True
except:
price_flag = False
cmd = "BUY " + symbol + " " + \
str(stock) + " " + str(price) + " " + \
str(uid)+"\n" # The message to be sent
elif len(parameters) == 4: # "BUY symbol pricepershare stockamount" case
symbol = str(parameters[1])
try:
stock = float(parameters[2])
if stock < 0:
raise("less than 0")
except:
while stock_flag == False:
try:
stock = float(
input("Please enter stock ammount as a float or integer\n"))
if stock > 0:
stock_flag = True
except:
stock_flag = False
try:
price = float(parameters[3])
except:
while price_flag == False:
try:
price = float(
input("Please enter stock price per share as a float or integer\n"))
if price > 0:
price_flag = True
except:
price_flag = False
cmd = "BUY " + symbol + " " + \
str(stock) + " " + str(price) + " " + \
str(uid)+"\n" # Message to be sent
elif len(parameters) >= 5: # "BUY symbol price per share stock amount uid" and corners case
symbol = str(parameters[1])
try:
stock = float(parameters[2])
except:
while stock_flag == False:
try:
stock = float(
input("Please enter stock ammount as a float or integer\n"))
if stock > 0:
stock_flag = True
except:
stock_flag = False
try:
price = float(parameters[3])
except:
while price_flag == False:
try:
price = float(
input("Please enter stock price per share as a float or integer\n"))
if price > 0:
price_flag = True
except:
price_flag = False
cmd = "BUY " + symbol + " " + \
str(stock) + " " + str(price) + " " + str(uid)+"\n"
sendMsg(cmd)
response = recieveMsg()
if response[0:3] == "200":
print(response[7:])
elif response[0:3] == "400":
print(response)
elif cmd.lower()[0:4] == "sell".lower():
parameters = cmd.split(" ")
price_flag = False
stock_flag = False
symbol = ""
if len(parameters) == 0 or len(parameters) == 1: # "SELL" and "SELL " case
symbol = str(input("Please enter stock symbol\n"))
# Ensure real positive numbers for price and stock amount, ensure integer for uid
while price_flag == False:
try:
price = float(
input("Please enter stock price per share as a float or integer\n"))
if price > 0:
price_flag = True
except:
price_flag = False
while stock_flag == False:
try:
stock = float(
input("Please enter stock ammount as a float or integer\n"))
if stock > 0:
stock_flag = True
except:
stock_flag = False
cmd = "SELL " + symbol + " " + \
str(stock) + " " + str(price) + " " + str(uid)+"\n"
elif len(parameters) == 2: # "Sell symbol" case
symbol = str(parameters[1])
# Ensure real positive numbers for price and stock amount, ensure integer for uid
while price_flag == False:
try:
price = float(
input("Please enter stock price per share as a float or integer\n"))
if price > 0:
price_flag = True
except:
price_flag = False
while stock_flag == False:
try:
stock = float(
input("Please enter stock ammount as a float or integer\n"))
if stock > 0:
stock_flag = True
except:
stock_flag = False
cmd = "SELL " + symbol + " " + \
str(stock) + " " + str(price) + " " + str(uid)+"\n"
elif len(parameters) == 3: # "SELL symbol stock" case
symbol = str(parameters[1])
# Ensure real positive numbers for price and stock amount, ensure integer for uid
try:
stock = float(parameters[2])
if stock < 0:
raise("less than 0")
except:
while stock_flag == False:
try:
stock = float(
input("Please enter stock ammount as a float or integer\n"))
if stock > 0:
stock_flag = True
except:
stock_flag = False
while price_flag == False:
try:
price = float(
input("Please enter stock price per share as a float or integer\n"))
if price > 0:
price_flag = True
except:
price_flag = False
cmd = "SELL " + symbol + " " + \
str(stock) + " " + str(price) + " " + str(uid)+"\n"
elif len(parameters) == 4: # "SELL symbol stock price" case
symbol = str(parameters[1])
# Ensure real positive numbers for price and stock amount, ensure integer for uid
try:
price = float(parameters[3])
except:
while price_flag == False:
try:
price = float(
input("Please enter stock price per share as a float or integer\n"))
if price > 0:
price_flag = True
except:
price_flag = False
try:
stock = float(parameters[2])
except:
while stock_flag == False:
try:
stock = float(
input("Please enter stock ammount as a float or integer\n"))
if stock > 0:
stock_flag = True
except:
stock_flag = False
cmd = "SELL " + symbol + " " + \
str(stock) + " " + str(price) + " " + str(uid)+"\n"
elif len(parameters) >= 5: # "SELL symbol stock price uid" and corner case
symbol = str(parameters[1])
# Ensure real positive numbers for price and stock amount, ensure integer for uid
try:
price = float(parameters[3])
except:
while price_flag == False:
try:
price = float(
input("Please enter stock price per share as a float or integer\n"))
if price > 0:
price_flag = True
except:
price_flag = False
try:
stock = float(parameters[2])
if stock < 0:
raise("less than 0")
except:
while stock_flag == False:
try:
stock = float(
input("Please enter stock ammount as a float or integer\n"))
if stock > 0:
stock_flag = True
except:
stock_flag = False
cmd = "SELL " + symbol + " " + \
str(stock) + " " + str(price) + " " + str(uid)+"\n"
sendMsg(cmd)
response = recieveMsg()
if response[0:3] == "200":
print(response[7:])
elif response[0:3] == "400" or response[0:3] == "401":
print(response)
else:
print(f"command '{cmd}' not recognized... please try again")
def cmdListen():
global listening
global message
listening = True
cmd = input("CMD>> ")
listening = False
message = cmd
# main client command loop - "quit" to quit the program and "shutdown" to shutdown the server
while connection:
# manage command listener
if listening == False:
if message != oldMessage:
oldMessage = message
executeThread = threading.Thread(
target=executeCMD, args=(message,))
executeThread.start()
executeThread.join()
if connection == False:
break
listenerThread = threading.Thread(
target=cmdListen, daemon=True, args=())
listenerThread.start()
# check for message from server
if connection == False:
break
try:
s.setblocking(False)
serverMSG = s.recv(2048, socket.MSG_PEEK)
s.setblocking(True)
if serverMSG.decode("utf-8") != "":
if serverMSG.decode("utf-8").strip() == "shutdown":
print("\nShutdown command received from server")
quitClient()
except BlockingIOError: # no message recieved
s.setblocking(True)
except Exception as e:
s.setblocking(True)
print(e)
quitClient()
# loop delay
time.sleep(0.1)