Simple introduction to socket programming in Ruby

Source: Internet
Author: User
Tags ftp http request socket split thread class tutorialspoint


This article mainly introduces the simple introduction of socket programming in Ruby, is the basic knowledge of Ruby network programming learning, need friends can refer to the



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 = 2000
 
s = TCPSocket.open(host, port)
 
while line = s.gets  # Read lines from the socket
 puts line.chop   # And print with platform line terminator
end
s.close        # Close the socket when 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(2000) # Socket to listen on port 2000
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(2000)  # Socket to listen on port 2000
loop {             # 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 = 80              # Default HTTP port
path = "/index.htm"         # The file we want 
 
# This is the HTTP request we send to fetch a file
request = "GET #{path} HTTP/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 first blank line into headers and 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.htm'         # The file we want 
 
http = Net::HTTP.new(host)     # Create a connection
headers, body = http.get(path)   # Request the file
if headers.code == "200"      # Check the status code  
 print body            
else               
 puts "#{headers.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.