Networking

Ruby’s networking capabilities are provided by the standard library rather than by core classes. For this reason, the subsections that follow do not attempt to enumerate each available class or method. Instead, they demonstrate how to accomplish common networking tasks with simple examples. Use ri for more complete documentation.

At the lowest level, networking is accomplished with sockets, which are a kind of IO object. Once you have a socket opened, you can read data from, or write data to, another computer just as if you were reading from or writing to a file. The socket class hierarchy is somewhat confusing, but the details are not important in the following examples. Internet clients use the TCPSocket class, and Internet servers use the TCPServer class (also a socket). All socket classes are part of the standard library, so to use them in your Ruby program, you must first write:

require 'socket'

A Very Simple Client

To write Internet client applications, use the TCPSocket class. Obtain a TCPSocket instance with the TCPSocket.open class method, or with its synonym TCPSocket.new. Pass the name of the host to connect to as the first argument and the port as the second argument. (The port should be an integer between 1 and 65535, specified as a Fixnum or String object. Different internet protocols use different ports. Web servers use port 80 by default, for example. You may also pass the name of an Internet service, such as “http”, as a string, in place of a port number, ...

Get The Ruby Programming Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.