Socket programming in Ruby

Source: Internet
Author: User
Tags tutorialspoint

Socket programming in Ruby

This article mainly introduces Socket programming in Ruby. It is a basic knowledge in Ruby network programming. For more information, see

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:

?

1

2

3

4

5

6

7

8

9

10

11

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 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.

?

1

2

3

4

5

6

7

8

9

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 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:

?

1

2

3

4

5

6

7

8

9

10

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

}

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:

?

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 = 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 rnrn"

 

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 ("rnrn", 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:

?

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 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

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

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.