Simple introduction to socket programming in Ruby _ruby topics

Source: Internet
Author: User
Tags thread class tutorialspoint

Ruby provides two access-level network services. At a lower level, you can access the underlying operating system, which enables both client and server-oriented connections and connectionless protocols to support basic sockets.

Ruby also has a library of libraries that provide a higher level of access to specific application-level network protocols, such as Ftp,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 between processes in one process, in the same machine, or on different machines.

Sockets can be implemented in many different types of channels: Unix master sockets, TCP,UDP, and so on. The socket library provides processing, and the remainder is used to handle common transmissions, as well as specific classes as a generic interface.

Socket related noun terms:

A simple client:

Here we will write a very simple client program that will open a connection to a given port and host. Ruby's Tcpsocket class provides an open function that opens a socket.

Tcpsocket.open (Hosname, Port) opens a TCP link to the hostname on port ports.

Once a socket is open, you can read it like any Io object. When you're done, remember to close it as if you need to close 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 library

hostname = ' localhost '
port =%

s = Tcpsocket.open (h OST, Port) while line

= s.gets  # Read lines to the socket
 puts Line.chop   # and print with platform line Terminator
End
S.close        # Close the socket was done

A simple server:

To write to an Internet server, we use the TCPServer class. The TCPServer object is a factory to create the Tcpsocket object.

Now call Tcpserver.open (hostname, the port function specifies that one of the ports serves you and creates a TCPServer object.

Next, call the Accept method to return the TCPServer object. This method waits for the client to connect to the specified port, and then returns a Tcpsocket object that represents the connection to the client.

Require ' socket '        # get sockets from stdlib

server = Tcpserver.open (watts) # socket to listen on port
loop  {             # 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 run in the background server and then run the above client to see the results.
Multi-Client TCP server:

Most servers on the Internet are designed to handle a large number of customer requests at any one time.

Ruby's thread class makes it easy to create multithreaded servers. Accept the request and immediately create a new execution thread to handle the connection while allowing the main program to wait for more connections:

Require ' socket '        # get sockets from stdlib

server = Tcpserver.open (watts)  # Socket to listen on port
l OOP {             # 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
}

In this example there is a fixed loop, and when Server.accept responds and immediately creates and launches a new thread to handle the connection, it is passed to the thread using the Connection object. The main program immediately loops back and waits for a new connection.

This approach means that using Ruby thread code is portable in the same way that it will run in Linux,os x and Windows.
a tiny web browser:

We can use the socket library to implement any Internet protocol. For example, a Web page that gets content in your code:

Require ' socket '
 
host = ' www.tutorialspoint.com '   # The Web server
port =              # Default HTTP port
Path = "/index.htm"         # The file we want # This is the 

HTTP request ' We send to fetch a file
request = ' Get #{path} HTT p/1.0\r\n\r\n "

socket = Tcpsocket.open (host,port) # Connect to server
socket.print (Request)        # Send Request
response = Socket.read       # Read complete response
# Split response at a-blank line into headers a nd body
headers,body = response.split ("\r\n\r\n", 2) 
print Body             # and display it

To implement a similar web client, you can use a pre-built library, such as net::http, to work with HTTP. Here is the code, which is equivalent to the previous code:

Require ' net/http '         # The library we need
host = ' www.tutorialspoint.com '   # The Web server
path = '/index.h TM '         # The file we want 

HTTP = net::http.new (host)     # Create A connection
headers, BODY = http.get (path) 
   
    # Request The file
if Headers.code = = "      Check the status code print body            
else                
 puts" #{head Ers.code} #{headers.message} "End 



   

Please check the similar library, Ftp,smtp,pop,imap protocol.

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.