kusor (owner)

Fork Of

gist: 89588 by tmm1 simple EM chat server

Revisions

  • 9a8abf tmm1 Thu Apr 02 18:04:41 -0700 2009
  • 6e18b8 tmm1 Thu Apr 02 17:54:16 -0700 2009
gist: 229816 Download_button fork
public
Public Clone URL: git://gist.github.com/229816.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
}