-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
38 lines (30 loc) · 1.51 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
import colorama
import tornado.ioloop
import tornado.web
import tornado.websocket
connections = []
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
global connections
print(f"{colorama.Fore.RESET}[{colorama.Fore.RED}SRVR{colorama.Fore.RESET}] {colorama.Fore.YELLOW}Opened new connection...{colorama.Fore.RESET}")
connections.append(self)
self.set_nodelay(True)
def on_message(self, message):
global connections
print(f"{colorama.Fore.RESET}[{colorama.Fore.RED}SRVR{colorama.Fore.RESET}] {colorama.Fore.YELLOW}Recieved (and broadcasting) new message...{colorama.Fore.RESET}")
for connection in connections:
try:
connection.write_message(message)
except Exception as e:
print(f"{colorama.Fore.RESET}[{colorama.Fore.RED}SRVR{colorama.Fore.RESET}] {colorama.Fore.YELLOW}Had an exception while sending message: {colorama.Fore.RESET} {e}")
def on_close(self):
print(f"{colorama.Fore.RESET}[{colorama.Fore.RED}SRVR{colorama.Fore.RESET}] {colorama.Fore.YELLOW}Closing a connection...{colorama.Fore.RESET}")
def check_origin(self, origin):
return True
if __name__ == "__main__":
app = tornado.web.Application([
(r"/", WebSocketHandler),
])
app.listen(80)
print(f"{colorama.Fore.RESET}[{colorama.Fore.RED}SRVR{colorama.Fore.RESET}] {colorama.Fore.YELLOW}Starting WebSocket server...{colorama.Fore.RESET}")
tornado.ioloop.IOLoop.current().start()