* io.c (rb_open_file): encoding in mode string was ignored if perm is
[ruby-svn.git] / sample / drb / dchats.rb
blob012dfeeebe7a427617c1f17b65566507700ab213
1 =begin
2  distributed Ruby --- chat server
3         Copyright (c) 1999-2000 Masatoshi SEKI 
4 =end
5 require 'thread'
6 require 'drb/drb'
8 class ChatEntry
9   include DRbUndumped
11   def initialize(server, there)
12     @server = server
13     @there = there
14     @name = there.name
15     @key = there.key = Time.now
16   end
17   attr :name, true
18   attr :there
20   def say(str)
21     @server.distribute(@there, str)
22   end
24   def listen(str)
25     @there.message(@key, str)
26   end
27 end
30 class ChatServer
31   def initialize
32     @mutex = Mutex.new
33     @members = {}
34   end
36   def add_member(there)
37     client = ChatEntry.new(self, there)
38     @mutex.synchronize do
39       @members[there] = client
40     end
41     client
42   end
44   def distribute(there, str)
45     name = @members[there].name
46     msg = "<#{name}> #{str}"
47     msg2 = ">#{name}< #{str}"
48     @mutex.synchronize do
49       for m in @members.keys
50         begin
51           if m == there
52             @members[m].listen(msg2)
53            else
54             @members[m].listen(msg)
55           end
56         rescue
57           p $!
58           @members.delete(m)
59         end
60       end
61     end
62   end
63 end
65 if __FILE__ == $0
66   here = ARGV.shift
67   DRb.start_service(here, ChatServer.new)
68   puts DRb.uri
69   DRb.thread.join
70 end