Skip to content

Instantly share code, notes, and snippets.

@tmm1
Created April 3, 2009 00:54
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save tmm1/89588 to your computer and use it in GitHub Desktop.
Save tmm1/89588 to your computer and use it in GitHub Desktop.
simple EM chat server
require 'rubygems'
require 'eventmachine'
module ChatClient
def self.list
@list ||= []
end
def post_init
@name = "anonymous_#{rand(99999)}"
ChatClient.list.each{ |c| c.send_data "#{@name} has joined.\n" }
ChatClient.list << self
end
def unbind
ChatClient.list.delete self
ChatClient.list.each{ |c| c.send_data "#{@name} has left.\n" }
end
def receive_data data
(@buf ||= '') << data
while line = @buf.slice!(/(.+)\r?\n/)
if line =~ %r|^/nick (.+)|
new_name = $1.strip
(ChatClient.list - [self]).each{ |c| c.send_data "#{@name} is now known as #{new_name}\n" }
@name = new_name
elsif line =~ %r|^/quit|
close_connection
else
(ChatClient.list - [self]).each{ |c| c.send_data "#{@name}: #{line}" }
end
end
end
end
EM.run{
EM.start_server '0.0.0.0', 8081, ChatClient
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment