Simple Ruby in the Socket programming tutorial _ruby Topics

Source: Internet
Author: User
Tags thread class server port

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

Ruby Unified support for network protocols for applications, such as FTP, HTTP, and so on.

Whether it's at the top or the bottom. Ruby provides some basic classes that allow you to interact with many protocols, such as tcp,udp,socks, without sticking to the network layer. These classes also provide a helper class that allows 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 is communicating through the transport layer, TCP and UDP encounter problems that simultaneously provide concurrent services for multiple application processes. Multiple TCP connections or multiple application processes may need to transmit data through the same TCP protocol port. To differentiate between different application processes and connections, many computer operating systems provide interfaces called sockets for applications that interact with the TCP/IP protocol, distinguishing between network traffic and connections between different application processes.

There are 3 main parameters: The destination IP address of the communication, the Transport Layer Protocol (TCP or UDP) used, and the port number used. The socket is intended to be "socket." By combining these 3 parameters with a "socket" socket, the application layer can communicate with the transport layer through the socket interface to distinguish the communication from different application processes or network connections, and realize the concurrent service of data transmission.

Sockets Lexical Analysis:

A simple client

Below we have written a simple client instance with a given host and port, and the Ruby Tcpsocket class provides an open method for opening a Socke.

Tcpsocket.open (Hosname, Port) opens a TCP connection.

Once you open a Socket connection, you can read it like an IO object, and when you're done, you need to close the connection like you closed the file.

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

Require ' socket '   # Sockets is a standard library
 
hostname = ' localhost '
port =
 
s = Tcpsocket.open (hostname, port) 
   while line = s.gets  # Read each row 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 a Tcpsocket factory object.

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

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

Require ' socket '        # get socket standard library
 
server = tcpserver.open # socket listening port for
loop {             # permanently running service
 client = server.accept    # waits for clients
 to connect 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 the client's connection, and the main thread waits for more connections.

Require ' socket '        # get socket standard library
 
server = Tcpserver.open  # socket listening port for
loop {             # Permanently running 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 connection
 end
}

In this example, the socket runs permanently, and when the server.accept receives a connection from the client, a new thread is created and immediately begins processing the request. The main program immediately loops back and waits for a new connection.
a tiny web browser

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

Require ' socket '
 
host = ' www.ziqiangxuetang.com '   # web server Port
=              * # default HTTP port
path = "/index.htm" c6/># want to get the file address
 
# This is an HTTP request
= ' Get #{path} http/1.0\r\n\r\n '
 
socket = Tcpsocket.open (host,port) # Connection Server
socket.print (request)        # send requests
response = Socket.read       # Read full response
# Split response at a Blank line into headers and the
headers,body = Response.split ("\r\n\r\n", 2)
print body             # output result

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

The following code is equivalent to the previous code:

Require ' net/http '         # We need the library
host = ' www.ziqiangxuetang.com '      # web server
path = '/index.htm '         # The files we want
 
http = net::http.new (host)     # Create connection
headers, BODY = http.get (path)   # request File
if Headers.code = = "200" c11/># detection Status Code
 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.