Created
November 4, 2011 03:07
-
-
Save andrewhavens/1338570 to your computer and use it in GitHub Desktop.
Buggy event machine code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' # I'm getting this error when I try to run this file: | |
require 'em-websocket' # websocket_server.rb:62: syntax error, unexpected $end, expecting keyword_end | |
require 'json' | |
class ChatMessage | |
attr_accessor :type, :username, :message | |
def initialize(msg_json) | |
msg = JSON.parse(msg_json) | |
@type = msg['type'] | |
@username = msg['username'] | |
@message = msg['message'] | |
end | |
def is_join? | |
if @type == 'join' | |
end | |
def to_s | |
if is_join? | |
return {:type => 'status', :username => @username, :message => "#{@username} has joined the chatroom"}.to_json | |
else | |
return {:type => 'message', :username => @username, :message => @message}.to_json | |
end | |
end | |
end | |
EventMachine.run do | |
@main_channel = EventMachine::Channel.new | |
@subscribers = [] | |
EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8100) do |ws| | |
ws.onopen do | |
subscriber_id = @main_channel.subscribe do |msg| | |
ws.send(msg) #main send method, gets called when @main_channel.push gets called | |
end | |
ws.onclose do | |
@main_channel.push ({:type => 'status', :message => "#{@subscribers[subscriber_id]} has left the chatroom"}.to_json) | |
@main_channel.unsubscribe(subscriber_id) | |
end | |
ws.onmessage do |msg_json| | |
message = ChatMessage.new(msg_json) | |
if (message.is_join?) | |
@subscribers[subscriber_id] = message.username | |
end | |
@main_channel.push message.to_s | |
end | |
end | |
end | |
puts "WebSocket server started at ws://0.0.0.0:8100" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment