-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
215 lines (157 loc) · 5.17 KB
/
server.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
from threading import Thread
import re
import socket
import signal
import time
import multiprocessing as mp
topics = {}
def timeout(func, args = (), kwds = {}, timeout = 1, default = None):
pool = mp.Pool(processes = 1)
result = pool.apply_async(func, args = args, kwds = kwds)
try:
val = result.get(timeout = timeout)
except mp.TimeoutError:
pool.terminate()
raise Exception
else:
pool.close()
pool.join()
return val
def send_ping(conn):
# server sends ping and wait for subscriber to wait for PONG response
conn.send(f"PING".encode())
host, port = conn.getpeername()
print(f"PING sent to {host}:{port}")
while True:
user_msg = conn.recv(1024).decode()
user_msg = str(user_msg)
if user_msg == "PONG":
print(f"> PONG from {host}:{port}")
break
def unsubscribe_topics(conn):
pass
for topicID in topics.keys():
unsubscribe_topic(topicID=topicID, conn=conn)
def handle_ping(conn):
while True:
# Send pingmessage to subscriber every 10 seconds
time.sleep(4)
host, port = conn.getpeername()
try:
# wait for subscriber to response to PING message
# If subscriber did not any response in 10 seconds, timeout will occur
timeout(send_ping, args = (conn,), timeout = 5, default = '')
except Exception as e:
# close the socket connection
conn.close()
unsubscribe_topics(conn)
print(f"timeout occured on {host}:{port} ...")
break
def send_msg_to_subscribers(topicID, msg):
topic = topics[topicID]
topic = list(topic)
# user connection
for subscriber_conn in topic:
subscriber_conn.send(f"{topicID}: {msg}".encode())
def unsubscribe_topic(topicID, conn):
topic = topics[topicID]
topic = list(topic)
try:
topic.remove(conn)
topics[topicID] = topic
except ValueError:
pass
def create_topic(topicID):
topics[topicID] = []
return True
def add_subscriber_to_topic(topicID, conn):
if topicID not in topics.keys():
create_topic(topicID)
topic = topics[topicID]
topic = list(topic)
topic.append(conn)
topics[topicID] = topic
return True
def handle_publisher_client(new_connection, new_addr, user_msg):
_, topicID, message = user_msg.split(" ")
try:
send_msg_to_subscribers(topicID=topicID, msg=message)
new_connection.send(
f"your message published successfully\n".encode()
)
except KeyError:
new_connection.send(
f"Topic Does not exist\n".encode()
)
except Exception as e:
print("eeee", e)
new_connection.send(
f"Something goes wrong\n".encode()
)
new_connection.close()
def handle_subscriber_client(new_connection, new_addr, user_msg):
topicsID = user_msg.split(" ")[1:]
for topicID in topicsID:
add_subscriber_to_topic(topicID=topicID, conn=new_connection)
new_connection.send(
f"subscribing on {' '.join(topicsID)}\n".encode()
)
while True:
user_msg = new_connection.recv(1024).decode()
user_msg = str(user_msg)
if user_msg.startswith("unsubscribe") and user_msg.split(" ") == 2:
_, topicID = user_msg.split(" ")
unsubscribe_topic(topicID=topicID, conn=new_connection)
def handle_client(newConn, addr):
user_msg = newConn.recv(1024).decode()
user_msg = str(user_msg)
if user_msg.startswith("publish"):
if len(user_msg.split(" ")) == 3:
handle_publisher_client(newConn, addr, user_msg)
else:
newConn.send(
f"Invalid input!!\nexiting...\n".encode()
)
newConn.close()
return
if user_msg.startswith("subscribe"):
if len(user_msg.split(" ")) >= 2:
client_ping_handler = Thread(
target=handle_ping,
args=(
newConn,
)
)
client_ping_handler.start()
handle_subscriber_client(newConn, addr, user_msg)
else:
newConn.send(
f"Invalid input!!\nexiting...\n".encode()
)
newConn.close()
def runner():
# next create a socket object
s = socket.socket()
print("Socket successfully created")
port = 12345
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("", port))
print("socket binded to %s" % (port))
# put the socket into listening mode
s.listen(5)
print("socket is listening")
while True:
# Establish connection with client.
conn, addr = s.accept()
address = str(addr[1])
print("Got connection from", address)
# send a thank you message to the client. encoding to send byte type.
client_handler = Thread(
target=handle_client,
args=(
conn,
address,
),
)
client_handler.start()
runner()