REST

Leave a comment

UDP Client and Server in Ruby

Leave a comment

In the previous section we looked at creating a basic TCP client using net/telnet. However, to demonstrate a basic client/server system, UDP is an ideal place to start. Unlike with TCP, UDP has no concept of connections, so it works on a simple system where messages are passed from place to another with no guarantee of them arriving. Whereas TCP is like making a phone call, UDP is like sending a postcard in the mail.
Creating a UDP server is easy. Let’s create a script named udpserver.rb:

require 'socket'
s = UDPSocket.new
s.bind(nil, 1234)
5.times do
  text, sender = s.recvfrom(16)
  puts text
end

This code uses Ruby’s socket library, a library that provides the lowest-level access to your operating system’s networking capabilities. socket is well suited for UDP, and in this example you create a new UDP socket and bind it to port 1234 on the local machine. You loop five times, accepting data in 16-byte chunks from the socket and printing it to the screen.

■ Note The reason for looping just five times is so that the script can end gracefully after it receives five
short messages. Later, however, we’ll look at ways to keep servers running permanently.

Now that you have a server, you need a client to send data to it. Let’s create udpclient.rb:

require 'socket'
s = UDPSocket.new
s.send("hello", 0, 'localhost', 1234)

This code creates a UDP socket, but instead of listening for data, it sends the string “hello” to the UDP server on localhost at port 1234. If you run udpserver.rb at the same time as udpclient.rb, “hello” should appear on the screen where udpserver.rb is running. You have successfully sent data across a network (albeit on the same machine) from a client to a server using UDP.
It’s possible, of course, to run the client and server on different machines, and if you have multiple machines at your disposal, all you need to do is change ‘localhost’ on the send method to the hostname or IP address of the machine where udpserver.rb is running.
As you’ve seen, UDP is simple, but it’s possible to layer more-advanced features on top of it. For example, because there is no connection involved, you can alternate between client and server modes with a single program, accomplishing a two-way effect.
You can demonstrate this easily by making a single program send and receive UDP data to and from itself:

require 'socket'
host = 'localhost'
port = 1234
s = UDPSocket.new
s.bind(nil, port)
s.send("1", 0, host, port)
5.times do
  text, sender = s.recvfrom(16)
  remote_host = sender[3]
  puts "#{remote_host} sent #{text}"
  response = (text.to_i * 2).to_s
  puts "We will respond with #{response}"
  s.send(response, 0, host, port)
end

■ Note In a real-world situation you would typically have two scripts, each on a different machine and
communicating between each other, but this example demonstrates the logic necessary to achieve that
result on a single machine for ease of testing.

UDP has some benefits in speed and the amount of resources needed, but because it lacks a state of connection and reliability in data transfer, TCP is more commonly used. Next we’ll look at how to create some simple TCP servers to which you can connect with net/telnet and other applications.

Uploading Files in Ruby

Leave a comment

Uploading files to an FTP server is only possible if you have write permissions on the server in the directory to which you want to upload. Therefore, none of the examples in this section will work unedited, as you can’t provide an FTP server with write access (for obvious reasons!).
Uploading is the exact opposite of downloading, and net/ftp provides putbinaryfile and puttextfile methods that accept the same parameters as getbinaryfile and get-textfile. The first parameter is the name of the local file you want to upload, the optional second parameter is the name to give the file on the remote server (defaults to thesame as the uploaded file’s name if omitted), and the optional third parameter for putbinaryfile is the block size to use for the upload. Here’s an upload example:

require 'net/ftp'
ftp = Net::FTP.new('ftp.domain.com')
ftp.passive = true
ftp.login
ftp.chdir('/your/folder/name/here')
ftp.putbinaryfile('local_file')
ftp.close

Downloading Files in Ruby

Leave a comment

Downloading files from an FTP server is easy if you know the filename and what type of file you’re trying to download. Net::FTP provides two useful methods to download files, getbinaryfile and gettextfile. Plain text files and binary files (such as images, sounds, or applications) are sent in a different way, so it’s essential you use the correct method. In most situations you’ll be aware ahead of time which technique is required. Here’s an example showing how to download a binary file from the official Ruby FTP server:

require 'net/ftp'
ftp = Net::FTP.new('ftp.ruby-lang.org')
ftp.passive = true
ftp.login
ftp.chdir('/pub/ruby/1.8')
ftp.getbinaryfile('1.8.2-patch1.gz')
ftp.close

Connection and Basic FTP Actions in Ruby

Leave a comment

Connecting to an FTP server with net/ftp using an FTP URL is a simple operation:

require 'net/ftp'
require 'uri'
uri = URI.parse('ftp://ftp.ruby-lang.org/')
Net::FTP.open(uri.host) do |ftp|
  ftp.login 'anonymous', 'me@privacy.net'
  ftp.passive = true
  ftp.list(uri.path) { |path| puts path }
end

File Transfers with FTP in Ruby

Leave a comment

File Transfer Protocol (FTP) is a basic networking protocol for transferring files on any TCP/IP network. Although files can be sent back and forth on the Web, FTP is still commonly used for large files, or for access to large file repositories that have no particular relevance to the Web. One of the benefits of FTP is that authentication and access control is built in.
The core part of the FTP system is an FTP server, a program that runs on a file server that allows FTP clients to download and/or upload files to that machine.
In a previous section of this chapter, “The open-uri Library,” we looked at using the open-uri library to retrieve files easily from the Internet.The open-uri supports HTTP, HTTPS, and FTP URLs, and is an ideal library to use if you want to download files from FTP servers with as little code as possible. Here’s an example:

require 'open-uri'
output = File.new('1.8.2-patch1.gz', 'w')
open('ftp://ftp.ruby-lang.org/pub/ruby/1.8/1.8.2-patch1.gz') do |f|
  output.print f.read
end
output.close

Sending Mail with ActionMailer in Ruby

Leave a comment

ActionMailer (http://wiki.rubyonrails.org/rails/pages/ActionMailer) makes sending e-mail more high-level than using the SMTP protocol (or net/smtp) directly. Instead of talking directly with an SMTP server, you create a descendent of ActionMailer::Base, implement a method that sets your mail’s subject, recipients, and other details, and then you call that method to send e-mail.
ActionMailer is a part of the Ruby on Rails framework (as covered in Chapter 13), but can be used independently of it. If you don’t have Ruby on Rails installed on your computer yet, you can install the ActionMailer gem with gem install actionmailer.
Here’s a basic example of using ActionMailer:

require ‘rubygems’
require ‘action_mailer’
class Emailer < ActionMailer::Base def test_email(email_address, email_body) recipients(email_address) from "me@privacy.net" subject "This is a test e-mail" body email_body end end Emailer.deliver_test_email('me@privacy.net', 'This is a test e-mail!') [/source]

Older Entries