home PYTHONJAVA
 

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:

OptionsDescription
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:

Instance

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 used in Ruby to write a simple service. The TCPServer object is a factory object for TCPSocket.

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

Next call TCPServer's accept method, which waits for a client to connect to the specified port and then returns a TCPSocket object indicating that it is connected to the client.

Instance

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 effect.


Multi-client TCP service

On the Internet, most services have a large number of client connections.

Ruby's Thread class makes it easy to create multithreaded services, one thread performs client connections, and the main thread is waiting for more connections.

Instance

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 example, the socket is running permanently, and when server.accept receives the client's connection, a new thread is created and the request is processed immediately. The main program loops back immediately and waits for a new connection.


Small web browser

We can use the socket library to implement any Internet protocol. The following code shows how to get the content of a webpage:

Instance

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 implement a web-like client, you can use a library pre-built for HTTP such as Net::HTTP.

The following code is equivalent to the previous code:

Instance

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 just a brief introduction to the application of sockets in Ruby. For more documentation, please 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.