RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Ruby Programming Language Enables Concise Network Programming : Page 2

Reduce development time by using Ruby to access network services. Not only is Ruby a high-performance programming language, but its concise programming notation also enables you to write programs quickly.


Implement a REST-Based Web Service

Representational State Transfer (REST) is a simple means for implementing Web services. While REST also supports HTTP authentication and PUT requests for sending data to a Web service, the examples in this section assume only the use of HTTP GET requests for Web services. The first simple example is a REST-based Web service that adds two numbers. The goal is to handle GET requests that look like this:

GET /add?x=123&y=9 HTTP/1.1

Since Ruby has great built-in support for regular expressions, you can start up the Ruby interactive interpreter IRB and experiment with a regular expression matcher until you get one that works:
Listing 4
irb irb(main):001:0> s="GET /add?x=123&y=9 HTTP/1.1" => "GET /add?x=123&y=9 HTTP/1.1" irb(main):002:0> re=/x=(\d+)\&y=(\d+)/ => /x=(\d+)\&y=(\d+)/ irb(main):003:0> x = re.match(s) => #<MatchData:0x4709c> irb(main):004:0> x[1,4] => ["123", "9"] irb(main):005:0> x[1] => "123" irb(main):006:0> x[2] => "9" irb(main):007:0>
Now you are ready for a server that is similar to the first example, but this example returns an XML payload instead of HTML:
Listing 5
require 'socket' server = TCPServer.new('', 9090) re=/x=(\d+)\&y=(\d+)/ while (session = server.accept) request = session.gets numbers = re.match(request) answer = numbers[1].to_i + numbers[2].to_i session.print "HTTP/1.1 200/OK\rContent-type: text/xml\r\n\r\n" session.puts "<add x=\"#{numbers[1]}\" y=\"#{numbers[2]}\" answer=\"#{answer}\" /> " session.close end
You could use the test client in Listing 2, but it is not a practical example. So you should change it slightly to accept a text string as an argument. You will need to URL encode the text string using code like this:

require 'CGI'
CGI.escape("1 2 3://:$")

This produces: "1+2+3%3A%2F%2F%3A%24".

The following example looks for a GET request like this:

GET /query=Why+did+the+dog+bite+the+cat%3F HTTP/1.1

Here, the query is URL encoded. The following example in Listing 6 simply finds the sub-strings "query=" and "http" and eats the text in between them as the input text:
Listing 6
require 'socket' require 'CGI' server = TCPServer.new('', 9090) while (session = server.accept) request = session.gets puts request index = request.index("query=") + 6 index2 = request.index(" HTTP") query = request[index..index2] puts query answer = CGI.unescape("I don't know the answer to: " + query) session.print "HTTP/1.1 200/OK\rContent-type: text/xml\r\n\r\n" session.puts "<answer>" + answer + "</answer>" session.close end

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date