Ruby Socket: An Introduction to Ruby Sockets and Socket Programming

ruby socketRuby is a programming language that was designed to be easy to read and easy to learn. It was developed in Japan during the 90s by Yukihiro “Matz” Matsumoto. The language is very popular today; it is used to develop web applications through the Ruby on Rails framework. Chances are, if you’re planning to work in the software industry, you will need to be conversant with the language and with Ruby on Rails. If you have learned a programming language before, it’ll be very easy for you to learn Ruby. Ruby is similar to other object-oriented programming languages like C and Java. However, the amount of code you need to get something done in Ruby is much less than what you need to type in C or Java. Ruby can also be learned as a first language. In fact, it is one of the easiest first languages to pick up, as there are several communities, learning resources and complete documentation about Ruby available online. If you want to learn more about Ruby, from the ground up, you can sign up for our introductory course in the language.

In this tutorial, we’ll take a look at socket programming in Ruby. While this tutorial is an introduction to socket programming, you do need to have a basic understanding of Ruby. This course can help you get started with Ruby, even if you have no prior programming experience. Alternatively you can read through this step by step guide to using Ruby.

What are Sockets?

So what are sockets exactly? According to the official definition of sockets, they are the endpoints of a bidirectional communication channel. To put it simply, they are the endpoints you can read from like a normal IO object. They act as the bridge to let same processes on the same machine or different processes on different machines communicate. Sockets can also communicate within a process, if a communication channel is established there.

Sockets are compatible with several different channel types. There are different types of sockets for this purpose, like UDP Socket, UNIX Socket and TCP Socket.  The type of communication for connectionless protocols is Socket::SOCK_DGRAM and the type of communication for connection oriented protocols is SOCK_STREAM. Sockets have their own set of vocabulary as well as methods, which you may need to know if you are going to work with them extensively. You can check the official documentation here for a full list.

We’ll briefly explain some of the more relevant terms in the socket vocabulary:

  • Domain: The domain is the family protocol that acts as a transport mechanism. Some of the constant domain values are PF_INET, PF_X25 and PF_UNIX.
  • Protocol: The protocol is almost always set to 0 and it’s used to identify a protocol variant.
  • Type: Type refers to the communication type we explained above. To reiterate: the type of communication for connectionless protocols is Socket::SOCK_DGRAM and the type of communication for connection oriented protocols is SOCK_STREAM.
  • Port: The port refers to the port the client is calling on. The server keeps a tab on several ports at once to catch the call. The port may be a string that contains a port number, a Fixnum port number or a service name.
  • Hostname: The hostname is the name (identifier) of the network interface handling the connection. It may be a string, which contains the name of the host, a quad address or an iPV6 address; or it may be a string that broadcasts an INADDR_BROADCAST address; or a string of length 0 that states INADDR_ANY; or it may be an integer that can be a binary address that fits in the host byte order.

Ruby lets you access network services at two levels: low and high. Low level access allows you to work with sockets the support the system you’re working on. It also allows you to set up client and server protocols for connection-oriented and connectionless channels. High level access (which is done by referring to the socket library) lets you work with network protocols like HTTP and FTP, among others. To learn more about how Ruby works, you can take this awesome course.

Some Simple Socket Programs

Now that you know the basic socket vocabulary, let’s take a few very simple programs that give you an idea of how sockets work.

The first program opens a working connection with a host on a certain port. The TCPSocket.open method is used for this. Once a socket is open, you can read data from it. After you are done reading the data and done using the connection, it’s recommended that you close the socket. A socket can be closed and opened like you would open and close a file.

This program will connect to a host, print a line and then close the socket:

require ‘socket’
hostname = ‘nameofhost’
port = 2000
s = TCPSocket.open (hostname, port)
while line = s.gets
puts line.chop
end
s.close

The first line (require ‘socket’) is used to refer to access the socket classes and methods present in the Ruby standard library. The port name and host number are input next (check the vocabulary for an explanation). Finally, the TCPSocket.open line opens a socket connection to the host. The final part of the program accepts and read inputs from the socket, prints it with the platform line terminator and then closes the socket. The s.close statement is used to close the socket. To see more examples of real Ruby programs, check out this Ruby practical training.

The second program lets you create a server (a TCPServer object) using the socket standard library. The TCPServer.open method is used to make the server object, just like we use the TCPSockset.open method to make a socket. Like a socket, a server should be created and then close once you are done using it. The client.close method closes the server. The code for it is:

require ‘socket’
server = TCPServer.open (2000)
loop do
client = server.accept
client.puts “The connection is now in place”
client.puts “The time is #(Time.now)”
client.puts “The connection is now closed. Thank you for connecting”
client.close
end

First, the socket classes and methods are accessed in the standard library by the require statement. Then, we specify a port (2000) on which the server will wait for a call from the client. Once the call has been accepted, after a wait, the method will return a TCPSocket object that stands for the connection to that particular client. The client will put three lines of text in the server.

If you don’t type the programs correctly, an error report will be generated. Exception handling in Ruby is separately documented for UNIX based systems and Windows based systems. The Windows WinSock reference page has information on errors- you can use it for trouble shooting if you encounter a difficult error. Ruby is compatible with most system platforms today – it’s possible to run a well designed program on a Windows system, UNIX-based system or a Mac OS system.

Sockets and socket programming in vast are that will take you some time to learn. We recommend that you peruse the official documentation for more details on socket programming.  Note that sockets can be used with other programming languages as well. To master Ruby in more detail, you can sign up for this advanced course. And, if you’re working on web development, this course will teach you everything you need to know to be able to develop your own web applications using the Ruby on Rails framework.