Ruby Socket Programming

Ruby gives two dimensions of access to the system, and at the base you can get to the working framework, which enables you to actualize essential attachment support for both customer and server for association situated and connectionless conventions.

Ruby brought together help for application organize conventions, for example, FTP, HTTP, and the sky is the limit from there.

Regardless of whether it is abnormal state or low-level. Ruby gives some essential classes that enable you to interface with numerous conventions, for example, TCP, UDP, SOCKS, and so on., without adhering to the system layer. These classes likewise give assistant classes that enable you to effectively peruse and keep in touch with the server.

Next we should figure out how to do Ruby Socket programming

What is Sockets

At the point when the application layer conveys information through the vehicle layer, TCP and UDP experience the issue of giving simultaneous administrations to numerous application forms in the meantime. Different TCP associations or various application procedures may need to exchange information over a similar TCP convention port. To recognize distinctive application procedures and associations, numerous PC working frameworks give an interface called Sockets to applications to collaborate with the TCP/IP convention, recognizing system correspondences and associations between various application forms.

The created attachment has three fundamental parameters: the goal IP address of the correspondence, the vehicle layer convention utilized (TCP or UDP), and the port number utilized. The first importance of Socket will be "attachment". By consolidating these three parameters and official to an "attachment" attachment, the application layer can speak with the vehicle layer through an attachment interface to recognize correspondence from various application procedures or system associations, and actualize simultaneous administrations for information transmission.

Sockets vocabulary analysis:

domain shows which convention family to utilize, normally PF_INET, PF_UNIX, PF_X25, etc.
typeSpecify the kind of attachment: SOCK_STREAM or SOCK_DGRAM. The Socket interface additionally characterizes the first Socket (SOCK_RAW), enabling the program to utilize low-level protocols
protocol is normally alloted an estimation of 0.
hostnameNetwork interface identifier:
  • String, which can be a hostname or IP address
  • String "<broadcast>", determines the INADDR_BROADCAST address.
  • 0 length string determining INADDR_ANY
  • An whole number that is translated as the paired location of the host byte request.
portport is the port number, every server will hear one out or increasingly port quantities of the customer association, a port number can be the port number of Fixnum, including the server name and port.

Simple client

The tailing we have composed a straightforward customer example for a given host and port. The Ruby TCPSocket class gives an open strategy to open an attachment.

TCPSocket.open(hosname, port ) Open a TCP association.

Once you open a Socket association, you can peruse it like an IO object. When you're set, you have to close the association as though you were shutting the record.

The following model exhibits how to associate with a particular host, read information from the attachment, lastly close the socket:


require ' socket' # Sockets is the standard library hostname = 'localhost' port= 2000 s = TCPSocket.open(hostname, port) while line = s.gets # from the socket Read each line of data puts line.chop # Print to the terminal end s.close # close the socket

Simple service

The TCPServer class can be utilized in Ruby to compose a straightforward administration. The TCPServer object is a processing plant object for TCPSocket.

Now we use TCPServer.open(hostname, port) to make a TCPServer object.

Next call TCPServer's acknowledge strategy, which trusts that a customer will associate with the predetermined port and afterward restores a TCPSocket object showing that it is associated with the customer.


require ' socket' # Get the socket standard library server = TCPServer.open(2000) # Socket listening port is 2000 loop { # Perpetual Run Service client= server.accept # Waiting for a client connection client.puts(Time.now.ctime) # Send time to client client.puts "Closing the connection. Bye!" client.close # Close client connections }

Now, run the above code on the server to see the impact.

Multi-customer TCP service

On the Internet, most administrations have an expansive number of customer associations.

Ruby's Thread class makes it simple to make multithreaded administrations, one string performs customer associations, and the principle string is hanging tight for more associations.


require ' socket' # Get the socket standard library server = TCPServer.open(2000) # Socket listening port is 2000 loop { # Perpetual Run Service Thread.start(server.accept) do |client| client.puts(Time.now.ctime) # Send time to client client.puts "Closing the connection. Bye!" client.close # Close client connections end }

In this model, the attachment is running forever, and when server.accept gets the customer's association, another string is made and the solicitation is prepared right away. The primary program circles back quickly and hangs tight for another association.

Small web browser

We can utilize the attachment library to actualize any Internet convention. The accompanying code tells the best way to get the substance of a webpage:


require ' socket' host = 'www.welookups.com' # web server port= 80 # default HTTP port path = "/index.htm" # File address you want to get # This is an HTTP request request= "GET #{path} HTTP/1.0\r\n\r\n" socket = TCPSocket.open(host,port) # Connecting to the server socket.print(request) # Send request response= socket.read # Read the full response # Split response at first blank line into headers and body headers,body = response.split("\ r\n\r\n", 2) print body # Output Results

To actualize a web-like customer, you can utilize a library pre-worked for HTTP, for example, Net::HTTP.

The following code is equal to the past code:


require ' net/http' # The library we need host = 'www.welookups.com' # web server path = '/index.htm' # The file we want http= Net::HTTP.new(host ) # Create a Connection headers, body = http.get(path) # Request File if headers.code == "200" # Detection Status Code print body else puts "#{headers.code} #{headers.message}" end

The above is only a short prologue to the utilization of attachments in Ruby. For more documentation, if you don't mind see: Ruby Socket library and class methods

welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.