I just learned DRb and made a chat system with it. Here're the codes:
Terminal 1:
require 'drb'
class A
def A.my_add(line, from)
puts from + ': ' + line
end
end
DRb.start_service('druby://127.0.0.1:61676', A)
B = DRbObject.new_with_uri('druby://127.0.0.1:61677')
while (line=gets).chomp != 'bye'
A.my_add line, "Terminal 1"
B.my_add line, "Terminal 1"
end
Terminal 2:
require 'drb'
class B
def B.my_add(line, from)
puts from + ': ' + line
end
end
DRb.start_service('druby://127.0.0.1:61677', B)
A = DRbObject.new_with_uri('druby://127.0.0.1:61676')
while (line=gets).chomp != 'bye'
A.my_add line, "Terminal 2"
B.my_add line, "Terminal 2"
end
I know it's very simple, just 2 terminals, and every messages are shown in all terminals with 'from' prefix. But an ugly thing is that I copied the same class and open different thread for each terminal, that's because I don't know how to print string to other machine's console. Thus, if the codes can be written like this:
class A
def A.my_add(line, from)
for <DRb Server and all clients> do
puts<to that terminal> from + ': ' + line
end
end
end
Then we can just maintain class A and use one thread. For every messages, just call A.my_add, then it will be printed to all terminals. I appreciate your help. Thanks!