Skip to content

Commit cfed82c

Browse files
committed
Added auto-reconnect in chat demo.
1 parent 74978aa commit cfed82c

File tree

3 files changed

+32
-10
lines changed

3 files changed

+32
-10
lines changed

django_socketio/example_project/chat/events.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,4 @@ def finish(request, socket, context):
5050
left = {"action": "leave", "name": user.name, "id": user.id}
5151
socket.broadcast_channel(left)
5252
user.delete()
53+

django_socketio/example_project/chat/static/js/chat.js

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,26 @@ $(function() {
5151
return false;
5252
});
5353

54-
var socket = new io.Socket();
55-
socket.connect();
56-
socket.on('connect', function() {
57-
socket.subscribe('room-' + window.room);
58-
showForm();
54+
$('#leave').click(function() {
55+
location = '/';
5956
});
6057

61-
socket.on('message', function(data) {
58+
var socket;
59+
60+
var connected = function() {
61+
socket.subscribe('room-' + window.room);
62+
if (name) {
63+
socket.send({room: window.room, action: 'start', name: name});
64+
} else {
65+
showForm();
66+
}
67+
};
68+
69+
var disconnected = function() {
70+
setTimeout(start, 1000);
71+
};
72+
73+
var messaged = function(data) {
6274
switch (data.action) {
6375
case 'in-use':
6476
alert('Name is in use, please choose another');
@@ -85,10 +97,16 @@ $(function() {
8597
addMessage(data);
8698
break;
8799
}
88-
});
100+
};
89101

90-
$('#leave').click(function() {
91-
location = '/';
92-
});
102+
var start = function() {
103+
socket = new io.Socket();
104+
socket.connect();
105+
socket.on('connect', connected);
106+
socket.on('disconnect', disconnected);
107+
socket.on('message', messaged);
108+
};
109+
110+
start();
93111

94112
});

django_socketio/example_project/chat/views.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,15 @@ def rooms(request, template="rooms.html"):
1313
context = {"rooms": ChatRoom.objects.all()}
1414
return render(request, template, context)
1515

16+
1617
def room(request, slug, template="room.html"):
1718
"""
1819
Show a room.
1920
"""
2021
context = {"room": get_object_or_404(ChatRoom, slug=slug)}
2122
return render(request, template, context)
2223

24+
2325
def create(request):
2426
"""
2527
Handles post from the "Add room" form on the homepage, and
@@ -31,6 +33,7 @@ def create(request):
3133
return redirect(room)
3234
return redirect(rooms)
3335

36+
3437
@user_passes_test(lambda user: user.is_staff)
3538
def system_message(request, template="system_message.html"):
3639
context = {"rooms": ChatRoom.objects.all()}

0 commit comments

Comments
 (0)