|
|
|
|
Ruby in a NutshellBy Yukihiro MatsumotoWith translated text by David L. Reynolds Jr. November 2001 0-59600-214-9, Order Number: 2149 218 pages, $24.95 |
Chapter 4 Excerpt
Standard Library ReferenceWe will now explore the useful libraries that come with the standard Ruby distribution, from network access via HTTP and CGI programming, to data persistence using the DBM library.
Standard Library
The Ruby standard library extends the foundation of the Ruby built-in library with classes and abstractions for a variety of programming needs, including network programming, operating system services, threads, and more. These classes provide flexible capabilities at a high level of abstraction, giving you the ability to create powerful Ruby scripts useful in a variety of problem domains, so you don't have to reinvent the wheel every time you have a problem to solve.
Many common tasks are performed by Ruby programmers all over the world. Some of these tasks include: network access such as TCP/IP and CGI, OS access, database access, controlling processes with threads, numeric calculations, implementing design classes and manipulating dates. These are used so frequently that they are included with all standard distributions of Ruby; when you access these classes and methods from your programs, you can be assured that they will be available from the Standard Library. Could you write these libraries yourself? Probably. Would you feel confident they have been exhaustively tested, optimized and debugged? Usually not. The Standard Library is a great time saver. And as Ruby grows and evolves, so will its Standard Library, to everyone's benefit.
Although not every library section will contain all of these entries, the basic format for each section is as follows:
- Required Library
- Example
- Inherited Class
- Class Methods
- Instance Methods
Network
Use Ruby's network classes to give your scripts the ability to speak basic protocols like TCP and UDP as a client, a server, or both. These libraries provide socket access to a variety of Internet protocols and classes that make access to those protocols easier. You can even crawl up the protocol stack and find support for higher-level protocols like FTP, HTTP, IMAP, and so on. All have an intuitive, transparent interface that won't get in your way. This is the largest group of libraries and one of the most frequently used.
Oh, and don't worry. There's support for doing web programming through the CGI, CGI::Cookie and CGI::Session classes.
BasicSocket
Socket-related superclass
BasicSocketis an abstract base class for Network Socket related classes. This class provides common behavior among Socket classes.Required Library
require 'socket' Inherited Class
IOClass Methods
BasicSocket::do_not_reverse_lookup- Returns true if query returns numeric address not host name.
BasicSocket::do_not_reverse_lookup=bool- Sets reverse_lookup status
Instance Methods
- s
.getpeername- Returns information on this connection's peer socket as a
structsockaddrpacked into a string.
- s
.getsockname- Returns information on s as a
struct sockaddrpacked into a string.
- s
.getsockopt(lev,optname)- Gets the specified socket option.
- s
.setsockopt(lev,optname,value)- Sets the specified socket option.
- s
.shutdown([how=2])- Shuts down the socket connection.
0shuts down receiving,1sending, and2both.
- s
.recv(len[,flags])- Receives data from s and returns it as a string.
- s
.send(mesg,flags[,to])- Sends data over the socket s, returning the length of the data sent. to may be a
struct sockaddrpacked into a string indicating the recipient address.
IPSocket
IP socket class
IPSocketclass is a base class ofTCPSocketandUDPSocket.IPSocketclass provides common behavior among IP (Internet Protocol) Sockets. Sockets classes in Ruby supports IPv6, if native platform supports it.Required Library
require 'socket' Inherited Class
BasicSocketClass Methods
IPSocket::getaddress(host)- Returns the IP address of the specified host. The IP address is returned as a string such as "
127.10.0.1" (IPv4) or "::1" (IPv6).
Instance Methods
- s
.addr- Returns an array containing information on the socket connection ("
AF_INET", port, host name, and IP address).
s = TCPSocket.open("www.ruby-lang.org", "http")
s.addr# => ["AF_INET", 4030, "dhcp198.priv.netlab.jp", "192.168.1.198"]
- s
.peeraddr- Returns an array containing information on the peer socket in the same format as with s
.addr.
s = TCPSocket.open("www.ruby-lang.org", "daytime")
s.recvfrom(255)
# => ["Wed Aug 1 00:30:54 2001\r\n", ["AF_INET", 13, "www", "210.251.121.214"]]
- s
.recvfrom(len[,flags])- Receives data and returns it in an array which also includes information on the sender's socket in the same format as with s
.addr.
UDPSocket
UDP socket class
UDPSocketis a class for UDP (User Datagram Protocol), which is connection-less, unreliable protocol.Required Library
require 'socket' Inherited Class
IPSocketClass Methods
UDPSocket::new([socktype=Socket::AF_INET])UDPSocket::open([socktype=Socket::AF_INET])Creates a UDP datagram socket.
Instance Methods
- s
.bind(host,port)- Binds the socket to port on host. host may be empty string ("") for
INADDR_ANY, or "<broadcast>" forINADDR_BROADCAST.
- s
.connect(host,port)- Connects the socket to port on host. host may be empty string ("") for
INADDR_ANY, or "<broadcast>" forINADDR_BROADCAST.
- s
.send(mesg,flags[,to])- s
.send(mesg,flags[,host,port])- Sends data on a socket s, returning the length of the data sent. If only two arguments are specified, the destination is assumed to be the port of the existing connection. Otherwise, it may be specified using a
struct sockaddrwhen calling the method with three arguments, or by indicating host and port when specifying four arguments.
TCPSocket
TCP/IP socket class
TCPSocketis a class for TCP (Transmission Control Protocol), which is connection-oriented, reliable protocol.Example
require "socket"host=(if ARGV.length == 2; ARGV.shift; else "localhost"; end)print("Trying ", host, " ...")STDOUT.flushs = TCPsocket.open(host, ARGV.shift)print(" done\n")print("addr: ", s.addr.join(":"), "\n")print("peer: ", s.peeraddr.join(":"), "\n")while gets( )s.write($_)print(s.readline)ends.closeRequired Library
require 'socket' Inherited Class
IPSocketClass Methods
TCPSocket::new(host,service)TCPSocket::open(host,service)- Opens a TCP connection to host for service, which may also be a port number.
TCPServer
TCP/IP server socket class
TCPServeris a class for server-side TCP sockets. ATCPServerwaits for client connection by accept method, then returns aTCPSocketobject connected to the client.Required Library
require 'socket' Example
require "socket"gs = TCPserver.open(0)addr = gs.addraddr.shift # removes "AF_INET"printf("server is on %s\n", addr.join(":"))while trueThread.start(gs.accept) do |s|print(s, " is accepted\n")while s.getss.write($_)endprint(s, " is gone\n")s.closeendendInherited Class
TCPSocketClass Methods
TCPServer::new([host="localhost",]service)TCPServer::open([host="localhost",]service)- Creates a server socket.
Instance Methods
s
.accept
- Waits for a connection and returns a new
TCPSocketobject once one is accepted.
UNIXSocket
UNIX domain socket class
UNIXSocketis a class for the UNIX domain, which can be specified by path.Required Library
require 'socket' Inherited Class
BasicSocketClass Methods
UNIXSocket::new(path)UNIXSocket::open(path)- Creates a Unix domain socket.
Instance Methods
- s
.addr- Returns an array containing information on the socket ("
AF_UNIX" and path).
- s
.path- Returns the path of the Unix domain socket.
- s
.peeraddr- Returns an array containing information on the peer socket in the same format as with s
.addr.
- s
.recvfrom(len[,flag0])- Receives data and returns it in an array which also includes information on the sender's socket in the same format as with s
.addr.
UNIXServer
UNIX domain server socket class
UNIXServeris a class for server-side UNIX domain sockets. AnUNIXServerwaits for client connection by accept method, then returns aUNIXSocketobject connected to the client.Required Library
require 'socket' Inherited Class
UNIXSocketClass Methods
UNIXServer::new(path)UNIXServer::open(path)- Creates a server socket.
Instance Methods
- s
.accept- Waits for a connection and returns a new
UNIXSocketobject once one is accepted.
Socket
General socket class
The Socket class is necessary to gain access to all the operating system's socket interfaces. Interface structures can be created by using
String#pack.Required Library
require 'socket' Inherited Class
BasicSocketClass Methods
Socket::for_fd(fd)- Creates a socket object corresponding to the file descriptor fd (an integer).
Socket::getaddrinfo(host,port[,family[,type[,proto[,flags]]]])- Returns an array containing socket address information (address family, port number, host name, host IP address, protocol family, socket type, and protocol).
Socket::getaddrinfo("www.ruby-lang.org", "echo", Socket::AF_INET, Socket::SOCK_DGRAM)
# => [["AF_INET", 7, "www", "210.251.121.214", 2, 2, 17]]
Socket::gethostbyaddr(addr[,type=Socket::AF_INET)- Returns an array containing socket address information (address family, port number, host name, host IP address, protocol family, socket type, and protocol).
Socket::getaddrinfo("www.ruby-lang.org", "echo", Socket::AF_INET, Socket::SOCK_DGRAM)
# => [["AF_INET", 7, "www", "210.251.121.214", 2, 2, 17]]
Socket::gethostbyname(name)- Returns an array containing host information retrieved from a host name.
Socket.gethostbyaddr(([127,0,0,1].pack("CCCC")))
# => ["ev", ["localhost", "ev.netlab.jp"], 2, "\177\000\000\001"]
Socket::gethostname- Returns the current host name.
Socket::getnameinfo(addr[,flags])- Returns an array containing the name of the host and service retrieved from the specified socket address information. addr may be a struct sockaddr packed into a string or an array (address family, port, and host name).
sockaddr = [Socket::AF_INET, 80, 127,0,0,1,""].pack("snCCCCa8")
Socket::getnameinfo(sockaddr) # => ["ev","www"]
Socket::getnameinfo(["AF_INET",80,"localhost"]) # => ["ev","www"]
Socket::getservbyname(service[,proto="tcp"])- Returns the port number for service and proto specified.
Socket::getservbyname("http") # => 80
Socket::new(domain, type, proto)Socket::open(domain, type, proto)- Creates a socket.
Socket::socketpair(domain,type,proto)Socket::pair(domain,type,proto)- Returns an array containing a pair of connected sockets.
Instance Methods
s.accept- Waits for a connection and, once one is accepted, returns a new socket object in an array which also includes a
structsockaddrpacked into a string.
- s
.addr- Synonym for s
.getsockname. Returnsstruct socaddrpacked in a string.
- s
.bind(addr)- Binds s to
addr, asockaddrstructure packed into a string.
- s
.connect(addr)- Connects s to
addr, asockaddrstructure packed into a string.
- s
.listen(backlog)- Specifies the size of the backlog queue.
- s
.recvfrom(len[,flags])- Receives data and returns it in an array which also includes information on the sender's socket in the form of a
sockaddrstructure packed into a string.
- s
.peeraddr- Synonym for s
.getpeername. Returnsstruct socaddrpacked in a string.
Constants
The following constants are defined for use in socket specifications.
AF_INETAF_UNIXMSG_OOBMSG_PEEKSOCK_DGRAMSOCK_STREAMSOL_SOCKETSO_KEEPALIVESO_LINGERSO_SNDBUF...These constants are also defined in the module
Socket::Constantsand may be used by including them in your code.Net::FTP
FTP connection class
Net::FTPis a class for FTP (File Transfer Protocol) client-side connection.Required Library
require 'net/ftp' Example
require 'net/ftp'ftp = Net::FTP::new("ftp.ruby-lang.org")ftp.login("anonymous", "matz@ruby-lang.org")ftp.chdir("/pub/ruby")tgz = ftp.list("ruby-*.tar.gz").sort.lastprint "the latest version is ", tgz, "\n"ftp.getbinaryfile(tgz, tgz)ftp.closeClass Methods
Net::FTP::new([host[,user[,passwd[,acct]]]])Net::FTP::open(host[,user[,passwd[,acct]]])- Creates a
Net::FTPobject.
Instance Methods
- f
.abort- Aborts the previous command.
- f
.acct(acct)- Sets the account.
- f
.chdir(path)- Changes the current directory.
- f
.close- Closes the connection.
- f
.closed?- Returns true if the connection is closed.
- f
.connect(host[,port=21])- Connects to host.
- f
.debug_mode- Returns the debug mode status.
- f
.debug_mode=bool- Sets the debug mode status.
- f
.delete(file)- Deletes a file.
- f
.getbinaryfile(remote,local[,blocksize=4096[,callback]])- f
.getbinaryfile(remote,local[,blocksize=4096]) {|data|...}- f
.gettextfile(remote,local[,callback])- f
.gettextfile(remote,local) {|data|...}- Retrieves a remote file from the server. If callback or a block is specified, it is executed with the retrieved data.
gettextfileperforms newline code conversion.
- f
.help([arg])- Displays help.
- f
.lastresp- Returns the server's last response.
- f
.list(path...)- f
.dir(path...)- f
.ls(path...)- Returns an array of file information in the directory. If a block is specified, it iterates through the listing.
f.list("/pub/ruby") # => ["drwxr-xr-x 2 matz users 4096 Jul 17 1998 1.0",...]
- f
.login([user="anonymous"[,passwd[,acct]]])- Logs into the server.
- f
.mkdir(path)- Creates a directory.
- f
.mtime(file[,local=false])- Returns the last modification time of file. If local is true, it is returned as a local time, otherwise as UTC (Coordinated Universal Time) time.
- f
.nlst([dir])- Returns an array of file names in the directory.
f.nlst("/pub/ruby") # => ["/pub/ruby/1.0",...]
- f
.putbinaryfile(remote,local[,blocksize=4096[,callback]])- f
.putbinaryfile(remote,local[,blocksize=4096]) {|data|...}- f
.puttextfile(remote,local[,callback])- f
.puttextfile(remote,local) {|data|...}- Transfers a file. If callback or a block is specified, the data to be sent is passed to it and it is run.
puttextfileperforms newline code conversion.
- f
.pwd- f
.getdir- Returns the current directory.
- f
.passive- Returns true if passive mode is enabled.
- f
.passive=bool- Sets passive mode on or off.
- f
.quit- Exits the FTP session.
- f
.rename(old,new)- Renames filename old to new.
- f
.rmdir(path)- Removes the directory specified by path.
- f
.resume- Returns true if resumption of file transfers is enabled.
- f
.resume=bool- Sets file transfer resumption on or off.
- f
.return_code- Returns the newline code of the current session.
- f
.return_code=ret- Sets the newline code of the current session.
- f
.size(file)- Returns the size of file.
- f
.status- Returns the status.
- f
.system- Returns system information.
- f
.welcome- Returns the server's welcome message.
Back to: Ruby in a Nutshell
© 2001, O'Reilly & Associates, Inc.
webmaster@oreilly.com