Simple introduction to socket programming in Ruby

Source: Internet
Author: User
Tags ftp http request require socket thread thread class server port

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:

?

1 2 3 4 5 6 7 8 9 10 11 Require ' socket ' # Sockets are in standard library hostname = ' localhost ' port = s = Tcpsocket.open (host, Port) While line = s.gets # Read lines to the socket puts Line.chop # and print with platform line Terminator End S.close # C Lose 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.

?

1 2 3 4 5 6 7 8 9 Require ' socket ' # Get sockets from Stdlib server = Tcpserver.open (watts) # socket to listen on port loop {# server s Run Forever client = server.accept # Wait for a client to connect client.puts (Time.now.ctime) # Send the "the" to "CLI" ENT 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:

?

1 2 3 4 5 6 7 8 9 10 Require ' socket ' # Get sockets from Stdlib server = Tcpserver.open (watts) # socket to listen on port loop {# server s 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:

?

1 2 3 4, 5 6 7 8 9 10 11 12 13 14 15 Require ' socket ' host = ' www.tutorialspoint.com ' # the Web server port = # Default HTTP Port path = '/index.htm ' # Th e file We want # This is the HTTP request ' we send to fetch a file request = ' Get #{path} http/1.0rnrn ' socket = TCPSOC Ket.open (host,port) # Connect to Server Socket.print (request) # Send Request response = Socket.read # read Complete respon SE # Split response at the blank of headers and body Headers,body = Response.split ("Rnrn", 2) Print body # and Di Splay 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:

?

1 2 3 4 5 6 7 8 9 10 11 Require ' net/http ' # The library we need host = ' www.tutorialspoint.com ' # the Web server path = '/index.htm ' # the file W E Want http = net::http.new (host) # Create a connection headers, BODY = http.get (path) # Request the file if Headers.cod e = "#" 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

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.