-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver_multithreaded.py
More file actions
183 lines (156 loc) · 6.01 KB
/
server_multithreaded.py
File metadata and controls
183 lines (156 loc) · 6.01 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
import socket
import threading
import queue
import time
ENCODING = 'utf-8'
HOST = 'localhost'
PORT = 8888
class Server(threading.Thread):
def __init__(self, host, port):
super().__init__(daemon=False, target=self.run)
self.host = host
self.port = port
self.buffer_size = 2048
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connection_list = []
self.login_list = {}
self.queue = queue.Queue()
self.shutdown = False
try:
self.sock.bind((str(self.host), int(self.port)))
self.sock.listen(10)
self.sock.setblocking(False)
except socket.error:
self.shutdown = True
if not self.shutdown:
listener = threading.Thread(target=self.listen, daemon=True)
receiver = threading.Thread(target=self.receive, daemon=True)
sender = threading.Thread(target=self.send, daemon=True)
self.lock = threading.RLock()
listener.start()
receiver.start()
sender.start()
self.start()
def run(self):
"""Main thread method"""
print("Enter \'quit\' to exit")
while not self.shutdown:
message = input()
if message == "quit":
self.sock.close()
self.shutdown = True
def listen(self):
"""Listen for new connections"""
print('Initiated listener thread')
while True:
try:
self.lock.acquire()
connection, address = self.sock.accept()
connection.setblocking(False)
if connection not in self.connection_list:
self.connection_list.append(connection)
except socket.error:
pass
finally:
self.lock.release()
time.sleep(0.050)
def receive(self):
"""Listen for new messages"""
print('Initiated receiver thread')
while True:
if len(self.connection_list) > 0:
for connection in self.connection_list:
try:
self.lock.acquire()
data = connection.recv(self.buffer_size)
except socket.error:
data = None
finally:
self.lock.release()
self.process_data(data, connection)
def send(self):
"""Send messages from server's queue"""
print('Initiated sender thread')
while True:
if not self.queue.empty():
target, origin, data = self.queue.get()
if target == 'all':
self.send_to_all(origin, data)
else:
self.send_to_one(target, data)
self.queue.task_done()
else:
time.sleep(0.05)
def send_to_all(self, origin, data):
"""Send data to all users except origin"""
if origin != 'server':
origin_address = self.login_list[origin]
else:
origin_address = None
for connection in self.connection_list:
if connection != origin_address:
try:
self.lock.acquire()
connection.send(data)
except socket.error:
self.remove_connection(connection)
finally:
self.lock.release()
def send_to_one(self, target, data):
"""Send data to specified target"""
target_address = self.login_list[target]
try:
self.lock.acquire()
target_address.send(data)
except socket.error:
self.remove_connection(target_address)
finally:
self.lock.release()
def process_data(self, data, connection):
"""Process received data"""
if data:
message = data.decode(ENCODING)
message = message.split(";", 3)
if message[0] == 'login':
tmp_login = message[1]
while message[1] in self.login_list:
message[1] += '#'
if tmp_login != message[1]:
prompt = 'msg;server;' + message[1] + ';Login ' + tmp_login \
+ ' already in use. Your login changed to ' + message[1] + '\n'
self.queue.put((message[1], 'server', prompt.encode(ENCODING)))
self.login_list[message[1]] = connection
print(message[1] + ' has logged in')
self.update_login_list()
elif message[0] == 'logout':
self.connection_list.remove(self.login_list[message[1]])
if message[1] in self.login_list:
del self.login_list[message[1]]
print(message[1] + ' has logged out')
self.update_login_list()
elif message[0] == 'msg' and message[2] != 'all':
msg = data.decode(ENCODING) + '\n'
data = msg.encode(ENCODING)
self.queue.put((message[2], message[1], data))
elif message[0] == 'msg':
msg = data.decode(ENCODING) + '\n'
data = msg.encode(ENCODING)
self.queue.put(('all', message[1], data))
def remove_connection(self, connection):
"""Remove connection from server's connection list"""
self.connection_list.remove(connection)
for login, address in self.login_list.items():
if address == connection:
del self.login_list[login]
break
self.update_login_list()
def update_login_list(self):
"""Update list of active users"""
logins = 'login'
for login in self.login_list:
logins += ';' + login
logins += ';all' + '\n'
self.queue.put(('all', 'server', logins.encode(ENCODING)))
# Create new server with (IP, port)
if __name__ == '__main__':
server = Server(HOST, PORT)