-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
83 lines (66 loc) · 2.08 KB
/
Copy pathserver.py
File metadata and controls
83 lines (66 loc) · 2.08 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
# import socket programming library
import socket
# import thread module
from _thread import *
import threading
print_lock = threading.Lock()
balance = 10000
# thread function
def threaded(c):
global balance
while True:
# data received from client
data = c.recv(1024)
if not data:
print('Bye')
# lock released on exit
print_lock.release()
break
# Check balance
if data == b'1':
# send back balance to client
print(balance)
c.send(bytes(str(balance), 'utf8'))
# Withdraw
if data == b'2':
withdrawal = c.recv(1024)
print("Withdraw: ", str(withdrawal, 'utf8'))
# Check if withdrawal amount is more than current balance.
if int(withdrawal) < balance:
balance = balance - int(withdrawal)
print("New balance: ", balance)
c.send(bytes(str(balance), 'utf8'))
else:
print("Withdrawal amount larger then current balance.")
c.send(bytes("No", 'utf8'))
# Deposit
if data == b'3':
deposit = c.recv(1024)
print("Deposit: ", str(deposit, 'utf8'))
balance = balance + int(deposit)
print("New balance: ", balance)
c.send(bytes(str(balance), 'utf8'))
# connection closed
c.close()
def Main():
host = ""
# reserve a port on your computer
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("socket binded to port", port)
# put the socket into listening mode
s.listen(5)
print("socket is listening")
# loop until client exits
while True:
# establish connection with client
c, addr = s.accept()
# lock acquired by client
print_lock.acquire()
print('Connected to :', addr[0], ':', addr[1])
# Start a new thread and return its identifier
start_new_thread(threaded, (c,))
s.close()
if __name__ == '__main__':
Main()