Permalink
Browse files

thread safety and adding multiple events

  • Loading branch information...
1 parent 09258f6 commit 6028f0d779dd3aff8a56a9165914b59bd837d79b @tenderlove committed Jul 7, 2012
@@ -11,3 +11,11 @@
*= require_self
*= require_tree .
*/
+
+li.nick {
+ color: orange;
+}
+
+li.join {
+ color: green;
+}
@@ -2,16 +2,35 @@
require 'observer'
require 'thread'
require 'erb'
+require 'mutex_m'
class ChatsController < ApplicationController
include ERB::Util
class Room
include Observable
+ include Mutex_m
- def say event
- changed
- notify_observers(event)
+ def add_observer(*args)
+ synchronize { super }
+ end
+
+ def delete_observer(*args)
+ synchronize { super }
+ end
+
+ def say who, msg
+ synchronize do
+ changed
+ notify_observers('event' => 'say', 'who' => who, 'msg' => msg)
+ end
+ end
+
+ def nick from, to
+ synchronize do
+ changed
+ notify_observers('event' => 'nick', 'from' => from, 'to' => to)
+ end
end
end
@@ -29,10 +48,17 @@ def show
queue = Queue.new
ROOM.add_observer queue, :push
+ stream = response.stream
+
response.headers['Content-Type'] = 'text/event-stream'
+ stream.write "retry: 10\n"
+ stream.write "event: join\n"
+ stream.write "data: #{JSON.dump({'who' => session[:name]})}\n\n"
+
while event = queue.pop
- response.stream.write "retry: 100\n"
- response.stream.write "data: #{JSON.dump(event)}\n\n"
+ event_name = event.delete('event')
+ stream.write "event: #{event_name}\n"
+ stream.write "data: #{JSON.dump(event)}\n\n"
end
ensure
# When (or if) the socket disconnects, remove the observer and close
@@ -47,9 +73,9 @@ def create
if params[:message] =~ /\A\/nick\s(\w+)/
old = session[:name]
session[:name] = $1
- ROOM.say('from' => h(old), 'to' => h(session[:name]))
+ ROOM.nick h(old), h(session[:name])
else
- ROOM.say('who' => h(session[:name]), 'msg' => h(params[:message]))
+ ROOM.say h(session[:name]), h(params[:message])
end
render :nothing => true
@@ -9,14 +9,25 @@
<script>
var source = new EventSource('/chat.json');
- source.addEventListener('message', function(e) {
+ source.addEventListener('say', function(e) {
var event = JSON.parse(e.data);
var chat = document.getElementById('chatroom');
- if(event.from) {
- $(chat).append("<li>" + event.from + " changed names to " + event.to + "</li>");
- } else {
- $(chat).append("<li>" + event.who + " said: " + event.msg + "</li>");
- }
+ $(chat).append("<li class='login'>" +
+ event.who + " said: " + event.msg + "</li>");
+ });
+
+ source.addEventListener('join', function(e) {
+ var event = JSON.parse(e.data);
+ var chat = document.getElementById('chatroom');
+ $(chat).append("<li class='login'>" +
+ event.who + " entered the room.</li>");
+ });
+
+ source.addEventListener('nick', function(e) {
+ var event = JSON.parse(e.data);
+ var chat = document.getElementById('chatroom');
+ $(chat).append("<li class='nick'>" +
+ event.from + " changed names to " + event.to + "</li>");
});
</script>

0 comments on commit 6028f0d

Please sign in to comment.