Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Networking in Ruby
2.1.
A Very Simple Client
2.2.
A Very Simple Server
2.3.
Datagrams
2.4.
Concept of a more Complex Client
2.5.
Why Multiplexing Server is needed?
2.6.
Fetching Web Pages
3.
Frequently Asked Questions
3.1.
What is Networking?
3.2.
What are sockets?
3.3.
What is TCP?
3.4.
What is UDP?
3.5.
What is a server?
4.
Conclusion
Last Updated: Mar 27, 2024

Networking in Ruby

Author Sanchit Kumar
0 upvote

Introduction

Ruby

Sharing is vital to businesses and other organizations in today's technologically advanced society. However, we require a quick and dependable method of sharing resources and information. So, the question is how to achieve this?

The answer is with the help of networking; we can share information and resources reliably and at high speed.

So, now let us learn about what networking in ruby is and how to accomplish everyday networking tasks with simple examples in code form.

Networking in Ruby

The standard library offers networking functionality for Ruby instead of core classes. Sockets, a type of IO object, are used to do networking at the lowest level. Once a socket is opened, you can read from or write data to another computer just like you were reading a file or writing to a file.

The two ends of a bidirectional communication channel are sockets. Sockets may communicate between two different processes on the same or different machines. TCP, UDP, and other channel types are just a handful of the various alternative socket implementations, along with Unix domain sockets. The socket provides a generic interface for processing the other transports, while specific classes are available for handling the common ones.

Major networking protocols in use nowadays are Transmission Control Protocol(TCP) and User Datagram Protocol (UDP).

  • TCP: Data can be delivered in two directions once a connection has been established since the Transmission Control Protocol (TCP) is connection-oriented.
     
  • UDP: Error-checking and recovery services are not necessary with User Datagram Protocol (UDP), a connectionless, more straightforward Internet protocol.


Note - Sockets, a type of IO object that is used for networking in ruby, let us build clients and servers for both connection-oriented and connectionless protocols.
The TCPSocket class is used by Internet clients, whereas the TCPServer class is used by Internet servers (also a socket). Since all socket classes are a part of the standard library you must first write the statement require'socket' in your Ruby program in order to use them.

A Very Simple Client

Simple client code that connects to a given host and port.


# Sockets are in the standard library
require 'socket'

# Open a socket to host and port (hostname,port)
s = TCPSocket.open(localhost, 8080)
# Read lines from the socket
while line = s.gets
 puts line.chop # And print with a platform line terminator
end
s.close
# Close the socket when done
You can also try this code with Online Ruby Compiler
Run Code


The open function to open such a socket is provided by the Ruby class TCPSocket. A TCP connection to the hostname on the port is opened via the TCPSocket.open(hostname, port) method. When a socket is open, you can read from it just like any other IO object. Remember to close it whenever you're through, just like you would a file.

A Very Simple Server

# Get sockets from stdlib
require 'socket'
 # Socket: to listen on port 8081
server = TCPServer.open(8081)

# servers run forever
loop {
# Wait for a client to connect
 client = server.accept
 # Send the current time to the client
 client.puts(Time.now.ctime)
 client.close # Disconnect from the client
}
You can also try this code with Online Ruby Compiler
Run Code


Run this code in another terminal window or in the background to test it. Run the straightforward client code from earlier using a command like this:

ruby client.rb localhost 8081

Output

Sat Jul  2 01:05:56 2022

Datagrams

As previously demonstrated, TCPSocket and TCPServer are used to implement the majority of Internet protocols. The UDP datagrams with the UDPSocket class provide a lower-overhead alternative. Computers can send discrete data packets to other computers via UDP without incurring the cost of a persistent connection.

Concept of a more Complex Client

A fully developed Internet client with a telnet-like interface establishes a connection to the given host and port, then begins a loop in which each line of input from the console is read, sent to the server, and then read and printed as the server responds.

Why Multiplexing Server is needed?

The straightforward time server shown previously would only provide the client with the time before cutting off communication. Numerous more advanced servers keep a connection open, and in order to be functional, they must permit multiple clients to join and communicate simultaneously.

Ways to do this - 

  • With threads—each client runs in its own thread
  • With Multithreaded server
  • With Multiplexing server

Fetching Web Pages

The socket library can be used to implement any Internet protocol.

The following code will retrieve the content of a website:
 

# The library we need
require 'net/http'

 # The web server
host = 'www.example.com'

# The file we want
path = '/index.html'

# Create a connection
http = Net::HTTP.new(host)

# Request the file
headers, body = http.get(path)

# Check the status code
if headers.code == "200"
 # NOTE: code is not a number!
 # Print body if we got it
 print body
else
 # Display error message
 puts "#{headers.code} #{headers.message}" 
end
You can also try this code with Online Ruby Compiler
Run Code

Also Read - Demultiplexer

Frequently Asked Questions

What is Networking?

Networking, usually referred to as computer networking, is the process of moving data between nodes in an information system through a common media. Networking includes managing, maintaining, and running the network infrastructure, software, and rules in addition to designing, building, and using the network.

What are sockets?

The two ends of a bidirectional communication channel are sockets. Sockets may communicate between two different processes on the same or different machines.

What is TCP?

Since Transmission Control Protocol (TCP) is connection-oriented, that means data can be transmitted in both ways after a link has been made. TCP is the ideal protocol for transporting information like still photographs, data files, and web pages because it contains built-in systems to check for faults and ensure that data will be sent in the order it was sent.

What is UDP?

User Datagram Protocol (UDP) is a more straightforward, connectionless Internet protocol that does not require error-checking or recovery services. With UDP, data is continuously delivered to the recipient, regardless of whether they receive it or not. There is no overhead for opening, maintaining, or ending a connection.

What is a server?

A computer program or device that offers a service to another computer program and its user, also known as the client, is referred to as a server.

Conclusion

In this article, we discussed Networking in Ruby. We started with a brief introduction about the socket, and networking protocols, writing Internet client applications, writing Internet servers and other concepts related to networking in ruby.

You can refer to Documentation of RubyOfficial Ruby FAQ and Learn Ruby with the Edgecase Ruby Koans to learn more about Ruby. 

Nevertheless, you may consider our paid courses to give your career an edge over others.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Coding Ninjas
Live masterclass