Introduction
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
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
}
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
Also Read - Demultiplexer