Latest web development tutorials

Ruby Socket Programming

Ruby provides two levels of access to network services, you can access the underlying operating system, it allows you to achieve the client and server support for the basic socket connection-oriented and connectionless protocols.

Ruby unified application support network protocols, such as FTP, HTTP and the like.

Whether top or bottom. ruby provides some basic classes, so you can use the interactive TCP, UDP, SOCKS, and many other protocols, without formality at the network layer. These classes also provide supplementary classes, so you can easily read and write to the server.

Next, let us learn how Ruby Socket Programming


What are Sockets

When the application layer data communication through the transport layer, TCP and UDP experience while providing services for multiple concurrent application process issues. Multiple TCP connections or multiple applications through the same process may require a TCP protocol port to transfer data. In order to distinguish between different application processes, and connections, many computer operating systems interact with applications TCP IP / protocol and provides an interface called a socket (Socket), the distinction between network communication and connectivity between different application processes for.

Generate socket, there are three main parameters: destination IP address of the traffic, the transport layer protocol (TCP or UDP) used and the port number. Socket is intended to "socket." By combining these three parameters, and a "socket" Socket bind, the application layer and the transport layer can be through the socket interface, the distinction between communication processes from different applications or network connections, concurrent data transmission services.

Sockets vocabulary analysis:

Options description
domain Specified protocol family is used, usually PF_INET, PF_UNIX, PF_X25, and so on.
type Specify the type of socket: SOCK_STREAM or SOCK_DGRAM, Socket interface also defines the raw Socket (SOCK_RAW), the program allows the use of low-level protocol
protocol Usually assigned 0.
hostname Network interface identifier:
  • String can be a hostname or IP address
  • The string "<broadcast>", specify INADDR_BROADCAST address.
  • Zero-length string that specifies INADDR_ANY
  • An integer interpreted as host byte order of binary address.
port port is the port number, and each server will listen to one or multiple port numbers for client connections, a port number can be Fixnum port number, it contains the server name and port.

Simple client

Below we through a given host and port to write a simple client instance, Ruby TCPSocket open class provides a way to open a socke.

TCPSocket.open (hosname, port) to open a TCP connection.

Once you open a Socket connection, you can read like IO object as it is completed, you need to close the file as close as the connection.

The following example demonstrates how to connect to a specific host, and read data from the socket, and finally close the socket:

require 'socket'      # Sockets 是标准库

hostname = 'localhost'
port = 2000

s = TCPSocket.open(hostname, port)

while line = s.gets   # 从 socket 中读取每行数据
  puts line.chop      # 打印到终端
end
s.close               # 关闭 socket 

Simple service

Ruby can be used TCPServer class to write a simple service. TCPServer objects are TCPSocket factory object.

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

The next call TCPServer accept method waits until a client connects to the specified port, and returns one TCPSocket object that represents the connection to the client.

require 'socket'               # 获取socket标准库

server = TCPServer.open(2000)  # Socket 监听端口为 2000
loop {                         # 永久运行服务
  client = server.accept       # 等待客户端连接
  client.puts(Time.now.ctime)  # 发送时间到客户端
  client.puts "Closing the connection. Bye!"
  client.close                 # 关闭客户端连接
}

Now, the above code runs on the server, view the results.


Multi-client TCP service

On the Internet, most services have a large number of client connections.

Ruby's Thread class can easily create multi-threaded, a thread of execution for client connections, and the main thread is waiting for more connections.

require 'socket'                # 获取socket标准库

server = TCPServer.open(2000)   # Socket 监听端口为 2000
loop {                          # 永久运行服务
  Thread.start(server.accept) do |client|
    client.puts(Time.now.ctime) # 发送时间到客户端
	client.puts "Closing the connection. Bye!"
    client.close                # 关闭客户端连接
  end
}

In this example, socket run forever, and when server.accept receiving client to connect to, a new thread is created and immediately begin processing the request. And now the main program loop back and wait for a new connection.


Tiny Web browser

We can use the socket library to implement any Internet Protocol. The following code shows how to get the page content:

require 'socket'
 
host = 'www.w3cschool.cc'     # web服务器
port = 80                           # 默认 HTTP 端口
path = "/index.htm"                 # 想要获取的文件地址

# 这是个 HTTP 请求
request = "GET #{path} HTTP/1.0\r\n\r\n"

socket = TCPSocket.open(host,port)  # 连接服务器
socket.print(request)               # 发送请求
response = socket.read              # 读取完整的响应
# Split response at first blank line into headers and body
headers,body = response.split("\r\n\r\n", 2) 
print body                          # 输出结果

To achieve a similar web client, you can use the pre-built library of HTTP such as Net :: HTTP.

The following code is equivalent to the preceding code:

require 'net/http'                  # 我们需要的库
host = 'www.w3cschool.cc'           #  web 服务器
path = '/index.htm'                 # 我们想要的文件 

http = Net::HTTP.new(host)          # 创建连接
headers, body = http.get(path)      # 请求文件
if headers.code == "200"            # 检测状态码
  print body                        
else                                
  puts "#{headers.code} #{headers.message}" 
end

Above we simply introduce Ruby in socket applications, further documentation, please see: Ruby libraries and the Socket class methods