forked from danidee10/Chatire
-
Notifications
You must be signed in to change notification settings - Fork 1
/
websocket.py
54 lines (42 loc) · 1.59 KB
/
websocket.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
"""Receive messages over from RabbitMQ and send them over the websocket."""
import sys
import pika
import uwsgi
def application(env, start_response):
"""Setup the Websocket Server and read messages off the queue."""
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost')
)
channel = connection.channel()
exchange = env['PATH_INFO'].replace('/', '')
channel.exchange_declare(
exchange=exchange, exchange_type='fanout'
)
# exclusive means the queue should be deleted once the connection is closed
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue # random queue name generated by RabbitMQ
channel.queue_bind(exchange=exchange, queue=queue_name)
uwsgi.websocket_handshake(
env['HTTP_SEC_WEBSOCKET_KEY'],
env.get('HTTP_ORIGIN', '')
)
def keepalive():
"""Keep the websocket connection alive (called every 30 seconds)."""
print('PING/PONG...')
try:
uwsgi.websocket_recv_nb()
connection.add_timeout(30, keepalive)
except OSError as error:
print(error)
sys.exit(1) # Kill process and force uWSGI to Respawn
keepalive()
while True:
for method_frame, _, body in channel.consume(queue_name):
try:
uwsgi.websocket_send(body)
except OSError as error:
print(error)
sys.exit(1) # Force uWSGI to Respawn
else:
# acknowledge the message
channel.basic_ack(method_frame.delivery_tag)