Simple Socket programming tutorial in Ruby, rubysocket Programming

Source: Internet
Author: User

Simple Socket programming tutorial in Ruby, rubysocket Programming

Ruby provides two levels of network access services. At the underlying layer, you can access the Operating System. This allows you to implement basic socket support for connection-oriented and non-connection protocols for clients and servers.

Ruby supports the network protocols of application programs, such as FTP and HTTP.

Whether it is high-level or underlying. Ruby provides some basic classes that allow you to use TCP, UDP, SOCKS, and many other protocols for interaction without sticking to the network layer. These classes also provide helper classes so that you can easily read and write the server.

Next, let's learn how to program Ruby Socket.
What is Sockets?

When the application layer uses the transport layer for data communication, TCP and UDP may encounter concurrent services for multiple application processes at the same time. Multiple TCP connections or multiple application processes may need to transmit data through the same TCP port. To differentiate different application processes and connections, many computer operating systems provide interfaces called Sockets for applications to interact with TCP/IP protocols, differentiate network communication and connections between processes of different applications.

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

Sockets vocabulary analysis:


Simple Client

Below we write a simple client instance through the given host and port. The Ruby TCPSocket class provides an open method to open a socke.

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

Once you open a Socket connection, you can read it like an IO object. After the connection is completed, you need to close the connection like closing the file.

The following example shows how to connect to a specified host, read data from the socket, and close the socket:

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

Simple Service

In Ruby, you can use the TCPServer class to write a simple service. The TCPServer object is the factory object of TCPSocket.

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

Next, call the accept method of TCPServer. The method waits until a client connects to the specified port, and then returns a TCPSocket object, indicating that it is connected to the client.

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

Now, run the above code on the server to check the effect.
Multi-client TCP Service

Most services on the Internet have a large number of client connections.

The Ruby Thread class can easily create multi-threaded services. One Thread executes the client connection, while the main Thread is waiting for more connections.

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

In this example, the socket runs permanently. When server. accept receives a connection from the client, a new thread is created and requests are processed immediately. The main program immediately loops back and waits for a new connection.
Tiny Web browsers

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

require 'socket'
 
host = 'www.ziqiangxuetang.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) # connect to the server
socket.print (request) # send request
response = socket.read # Read the complete response
# Split response at first blank line into headers and body
headers, body = response.split ("\ r \ n \ r \ n", 2)
print body # output

To implement a web-like client, you can use a pre-built library for HTTP, such as Net: HTTP.

The following code is equivalent to the previous Code:

require 'net / http' # libraries we need
host = 'www.ziqiangxuetang.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" # detect status codes
  print body
else
  puts "# {headers.code} # {headers.message}"
end 



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.