Ruby Distributed Object

Source: Internet
Author: User

Finally, let's look at distributed programming in ruby. Nowadays, the network is very common. Sometimes we want to transmit various objects on the network, but unfortunately, protocols like CORBA and RMI are very laborious to use and require special coding, exception handling, and the interface must be defined before any call.

Ruby has a simple solution to this problem, eliminating the complexity of the above method. Distributed Ruby (also called DRB or druby) is an independent library written completely in ruby, you can transmit various objects (Ruby objects) in different Ruby processes through TCP, and only a few steps are required.

Listing 8 shows an example in which the server shares an object. With this object, you can get the server time. Rows 3rd to 7th define the object to be shared when the local time is obtained. Rows 9th bind the object to a DRB server (in this example, the port is 2222 ), because the server program is in an independent thread, ensure that the main program can exit after the thread ends.

 

Listing 8: A simple distributed Ruby Server

 1   require 'drb' 2 3   class Info 4     def get_time 5       "It is now #{Time.now}" 6     end 7   end 8 9   DRb.start_service("druby://your.host.name:2222", Info.new)10   DRb.thread.join

Listing 9 is a client program, which is also very simple, with 4th rowsDrbobjectThe call establishes a connection with the remote server and returns a proxy of the remote object. Then, you can call the remote object method just like calling a local object.

 

Listing 9: A simple distributed Ruby Client

 1   require 'drb' 2 3   DRb.start_service 4   info = DRbObject.new(nil, "druby://your.host.name:2222") 5 6   3.times do  7     puts info.get_time 8     sleep 2 9   end 

 

Next let's take a look at another interesting thing, tuplesapces, which was first proposed by David Gelernter in the Linda system. tuplespaces is like a shared BBS system, and the program can post messages to it, or get a message from it. The message mentioned here is an array composed of some values. The out method is used to write messages to tuplespace. Therefore, the following code creates a tuplespace containing four pieces of content:

 

require 'tuplespace'ts = TupleSpace.new  ts.out  [ "dave", "car", "blazer" ]ts.out  [ "dave", "computer", "dell" ]ts.out  [ "andy", "car", "explorer" ]ts.out  [ "andy", "os", "linux" ]

What makes tuplespaces interesting is that if you want to obtain the content in it, you can retrieve it based on the content itself (through matching) instead of the address. The tuplespace implemented by ruby is more powerful. The matching mode for obtaining messages can be values, object classes, regular expressions, range, and so on. Nil indicates that you do not care about what its content is, that is, everything matches nil. To obtain the message content, you can use the in method. If the pattern specified in the in method can be found in tuplespace, the matched item will be deleted from tuplespace, and return this item to the caller. Otherwise, in will wait until a matched project appears. If multiple records match the pattern specified in, a random record is returned.

Continue with the previous example. The following example reads the stored records from tuplespace. Note that the last statement uses a regular expression as the matching mode.

# read one of Dave's possessionsres1 = ts.in ["dave", nil, nil]# someone owning a carres2 = ts.in [nil, "car", nil]# a possession containing the "x" or "z"res3 = ts.in [nil, nil, /[xz]/]

Starting from this simple example, you can easily compile complex, collaborative, and parallel systems.

For example, you can use tuplespace to solve complex AI problems. A process can combine a set of data and put it into tuplespace to generate a problem. Other processes can read it from tuplespace in a matched manner to solve the problem; when a process gets an error, it may also divide the problem into smaller ones and put them in tuplespace. Other processes obtain this problem again, and then solve them or continue to break down these problems.

This process continues until all problems are resolved.

To complete this article, we will use DRB and tuplespace to write a simple P2P chat program. This system will store messages consisting of three elements in tuplespace, that is, the message sender, receiver and message content.

The client program is in List 10. The client runs together with two threads. The sending thread is the main thread and the creation of the receiving thread is shown in it. The sending thread ranges from 16th rows to 22 rows. It reads strings from the user's console in the following format:

to:  message text

To is the recipient's name. The input in line 17th is divided into two parts: the first part is the name, and the rest is the message content. Then, lines 19th form an array of the message and write it into tuplespace.

 

Listing 10: A chat client based on tuplespaces

 1   require 'drb' 2   require 'tuplespace' 3 4   DRb.start_service 5   ts = DRbObject.new(nil, / "druby://server.host:12321") 6 7   my_name = ARGV[0] 8 9   Thread.new do10     loop do11       from, unused, line = ts.in / [ nil, my_name, nil ]12       puts "#{from} says: #{line}"13     end14   end1516   while line = gets17     to, text = line.split(/:/, 2)18     if text19       ts.out [ my_name, to, text ]20     else21       puts '** use   "to: message"'22     end23   end

The receiving thread is also very simple. Lines 9th to 14 run a simple loop to read data from tuplespace. The matching condition is that the message receiver is our own name and the result is printed on the console.

 

Tuplespaces requires a server to store tuples. In Ruby, the DRB server is used to store tuplespace objects. You can use the following code:

require 'drb'require 'tuplespace'DRb.start_service("druby://server.host:12321", /   TupleSpace.new)DRb.thread.join

First run the server program, then run the client, and specify the name you want to use as the parameter in the client program.

If you run it, you will find that if you are not online, the server will save the message to you on the server. Our application won't replace Yahoo IM, jabber, or IRC, but this code is very useful.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.