Introduction to Socket programming in Ruby and rubysocket Programming

Source: Internet
Author: User
Tags tutorialspoint

Introduction to Socket programming in Ruby and rubysocket Programming

Ruby provides two access-level network services. At a lower level, you can access the underlying operating system, which supports basic Sockets for clients and servers with connection-free protocols.

Ruby also has libraries that provide more advanced network protocols for accessing specific applications, such as FTP and HTTP.

This tutorial introduces the concept of Ruby Socket programming and explains a simple example.
What is Sockets?

A socket is the endpoint of a two-way communication channel. The socket can communicate with each other in a process, process on the same machine, or process on different machines.

Sockets can implement many different types of channels: Unix Main Control sockets, TCP, UDP, and so on. The socket Library provides processing, and the rest are used to process common transmission, as well as specific classes as a common interface.

Socket terminology:

A simple client:

Here, we will write a very simple client program, which will open a connection to a given port and host. Ruby's TCPSocket class provides open functions to open a socket.

TCPSocket. open (hosname, port) open a TCP link to hostname in port.

Once a socket is opened, it can be read as any IO object. Remember to close it, because it is like closing a file.

The following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits:

require 'socket'   # Sockets are in standard libraryhostname = 'localhost'port = 2000s = TCPSocket.open(host, port)while line = s.gets  # Read lines from the socket puts line.chop   # And print with platform line terminatorends.close        # Close the socket when done

A simple server:

To write data to an internet server, we use the TCPServer class. The TCPServer object is a factory used to create a TCPSocket object.

Call the TCPServer. open (hostname, port function to specify a port to serve you, and create a TCPServer object.

Next, call the accept method to return the TCPServer object. This method will wait for the client to connect to the specified port, and then return a TCPSocket object indicating to connect to the client.

require 'socket'        # Get sockets from stdlibserver = TCPServer.open(2000) # Socket to listen on port 2000loop {             # Servers run forever client = server.accept    # Wait for a client to connect client.puts(Time.now.ctime) # Send the time to the client client.puts "Closing the connection. Bye!" client.close         # Disconnect from the client}

Now it runs on the backend server and then runs the result displayed on the client above.
Multi-client TCP Server:

Most Internet servers are designed to process a large number of customer requests at any time.

The Ruby Thread class allows you to easily create multi-threaded servers. Accept the request, and immediately create a new execution thread to process the connection, and allow the main program to wait for more connections:

require 'socket'        # Get sockets from stdlibserver = TCPServer.open(2000)  # Socket to listen on port 2000loop {             # Servers run forever Thread.start(server.accept) do |client|  client.puts(Time.now.ctime) # Send the time to the client client.puts "Closing the connection. Bye!"  client.close        # Disconnect from the client end}

There is a fixed loop in this example. When server. accept responds and immediately creates and starts a new thread to process the connection, it uses the connection object to pass to the thread. The main program returns immediately after the loop and waits for a new connection.

This method means that the Ruby thread code can be transplanted and run in Linux, OS X, and Windows in the same way.
A tiny Web browser:

We can use the socket library to implement any Internet protocol. For example, the webpage that obtains content in the Code:

require 'socket' host = 'www.tutorialspoint.com'   # The web serverport = 80              # Default HTTP portpath = "/index.htm"         # The file we want # This is the HTTP request we send to fetch a filerequest = "GET #{path} HTTP/1.0\r\n\r\n"socket = TCPSocket.open(host,port) # Connect to serversocket.print(request)        # Send requestresponse = socket.read       # Read complete response# Split response at first blank line into headers and bodyheaders,body = response.split("\r\n\r\n", 2) print body             # And display it

To implement similar web clients, you can use a pre-built library, such as Net: HTTP and HTTP. The following is the code, which is equivalent to the previous Code:

require 'net/http'         # The library we needhost = 'www.tutorialspoint.com'   # The web serverpath = '/index.htm'         # The file we want http = Net::HTTP.new(host)     # Create a connectionheaders, body = http.get(path)   # Request the fileif headers.code == "200"      # Check the status code   print body            else                 puts "#{headers.code} #{headers.message}" end

Check Similar libraries, FTP, SMTP, POP, and IMAP protocols.

 

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.