Created
April 3, 2009 00:54
-
-
Save tmm1/89588 to your computer and use it in GitHub Desktop.
simple EM chat server
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' | |
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