-
Notifications
You must be signed in to change notification settings - Fork 8
/
views.py
110 lines (78 loc) · 2.95 KB
/
views.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
import time
from simplejson import dumps
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template import RequestContext
# ZeroMQ Connection
from gevent import spawn
from gevent_zeromq import zmq
context = zmq.Context()
publisher = context.socket(zmq.PUB)
publisher.bind("tcp://127.0.0.1:5000")
ACTIVE_ROOMS = set([])
# Message Coroutines
def send_message(socket, room, text):
socket.send_unicode("%s:%s" % (room, text))
def message_listener(socketio, room):
# For too many threads spawning new connection will cause a
# "too many mailboxes" error, but for small amounts of
# threads this is fine.
subscriber = context.socket(zmq.SUB)
subscriber.connect("tcp://127.0.0.1:5000")
# setsockopt doesn't like unicode
subscriber.setsockopt(zmq.SUBSCRIBE, str(room))
socketio.send({'message': 'connected: ' + room})
while True:
msg = subscriber.recv()
if msg:
socketio.send({'message': msg.split(":")[1]})
# Room Coroutines
def new_room(socket, room_name):
socket.send("room:%s" % str(room_name))
def room_listener(socketio):
# For too many threads spawning new connection will cause a
# "too many mailboxes" error, but for small amounts of
# threads this is fine.
subscriber = context.socket(zmq.SUB)
subscriber.connect("tcp://127.0.0.1:5000")
subscriber.setsockopt(zmq.SUBSCRIBE, 'room')
while True:
msg = subscriber.recv()
if msg:
socketio.send({'room_name': msg.split(":")[1]})
time.sleep(5)
def room(request, room_name=None, template_name='room.html'):
context = {
'room_name': room_name,
'initial_rooms': dumps(list(ACTIVE_ROOMS)),
}
if room_name not in ACTIVE_ROOMS:
spawn(new_room, publisher, room_name)
ACTIVE_ROOMS.add(room_name)
return render_to_response(template_name, context,
context_instance=RequestContext(request))
def room_list(request, template_name='room_list.html'):
context = {
'initial_rooms': dumps(list(ACTIVE_ROOMS)),
}
return render_to_response(template_name, context,
context_instance=RequestContext(request))
# SocketIO Handler
def socketio(request):
socketio = request.environ['socketio']
while True:
message = socketio.recv()
if len(message) == 1:
action, arg = message[0].split(':')
if action == 'subscribe':
if arg == 'rooms':
spawn(room_listener, socketio)
else:
spawn(message_listener, socketio, arg)
elif action == 'message':
room, text = arg.split(',')
#timestamp = time.strftime("(%H.%M.%S)", time.localtime())
ip_addr = request.META['REMOTE_ADDR']
message = "(%s) %s" % (ip_addr, text)
spawn(send_message, publisher, room, message).join()
return HttpResponse()