Ruby Socket Programming

Ruby provides two levels of access to the network, and at the bottom you can access the operating system, which allows you to implement basic socket support for both client and server for connection-oriented and connectionless protocols.

Ruby unified support for application network protocols such as FTP, HTTP, and more.

Whether it is high-level or low-level. Ruby provides some basic classes that allow you to interact with many protocols, such as TCP, UDP, SOCKS, etc., without having to stick to the network layer. These classes also provide helper classes that allow you to easily read and write to the server.

Next let's learn how to do Ruby Socket programming

What is Sockets

When the application layer communicates data through the transport layer, TCP and UDP encounter the problem of providing concurrent services for multiple application processes at the same time. Multiple TCP connections or multiple application processes may need to transfer data over the same TCP protocol port. To distinguish between different application processes and connections, many computer operating systems provide an interface called Sockets for applications to interact with the TCP/IP protocol, distinguishing between network communications and connections between different application processes.

The generated socket has three main parameters: the destination IP address of the communication, the transport layer protocol used (TCP or UDP), and the port number used. The original meaning of Socket is "socket". By combining these three parameters and binding to a "socket" socket, the application layer can communicate with the transport layer through a socket interface to distinguish communication from different application processes or network connections, and implement concurrent services for data transmission.

Sockets vocabulary analysis:

domain indicates which protocol family to use, usually PF_INET, PF_UNIX, PF_X25, and so on.
typeSpecify the type of socket: SOCK_STREAM or SOCK_DGRAM. The Socket interface also defines the original Socket (SOCK_RAW), allowing the program to use low-level protocols
protocol is usually assigned a value of 0.
hostnameNetwork interface identifier:
  • String, which can be a hostname or IP address
  • String "<broadcast>", specifies the INADDR_BROADCAST address.
  • 0 length string specifying INADDR_ANY
  • An integer that is interpreted as the binary address of the host byte order.
portport is the port number, each server will listen to one or more port numbers of the client connection, a port number can be the port number of Fixnum, including the server name and port.

Simple client

The following we have written a simple client instance for a given host and port. The Ruby TCPSocket class provides an open method to open a socket.

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

Once you open a Socket connection, you can read it like an IO object. When you're done, you need to close the connection as if you were closing the file.

The following example demonstrates how to connect to a specific host, read data from the socket, and finally 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.