Create simplest chat system with ruby DRb only

449 Views Asked by At

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!

1

There are 1 best solutions below

0
On

This is how I would go about doing this:

The right approach is this: Each system will have a unique IP and all the communication uses the same port. So, each terminal will have to do this: 1. Find the ip of the local system and put that in your start_service routine automatically. 2. Define one port for sending and one port for receiving. 3. Run the DRB server.

To communicate to a specified terminal1 to terminal2: Use the send port in terminal1 to send the message to the receiving port in terminal2.

For more than one terminals communications: You have the list of terminals, which maps names to an IP address. You can traverse the list of the terminals to send a message to the receiver port.