发布于 2015-07-11 02:40:38 | 261 次阅读 | 评论: 0 | 来源: 网络整理

Ruby提供了两个访问级别的网络服务。在一个较低的水平,可以访问底层的操作系统,它可以实现面向连接和无连接协议的客户端和服务器支持基本的socket。

Ruby也具有程序库,提供更高级别的访问特定的应用程序级的网络协议,如FTP,HTTP等。

这篇教程介绍 Ruby Socket编程概念及讲解一个简单的实例。 

什么是Sockets?

套接字是一个双向通信信道的端点。socket能在一个进程,进程在同一台机器之间,或在不同的机器上的进程之间的进行通信。

套接字可实施过许多不同类型的通道:Unix主控套接字,TCP,UDP等等。套接字库提供了处理,其余的用于处理常见的传输,以及作为一个通用的接口的具体类。

套接字相关名词术语:

术语 描述
domain The family of protocols that will be used as the transport mechanism. These values are constants such as PF_INET, PF_UNIX, PF_X25, and so on.
type The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
protocol Typically zero, this may be used to identify a variant of a protocol within a domain and type.
hostname The identifier of a network interface:
  • A string, which can be a host name, a dotted-quad address, or an IPV6 address in colon (and possibly dot) notation

  • A string "<broadcast>", which specifies an INADDR_BROADCAST address.

  • A zero-length string, which specifies INADDR_ANY, or

  • An Integer, interpreted as a binary address in host byte order.

port Each server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service.

一个简单的客户端:

在这里,我们将编写一个非常简单的客户端程序,这将打开一个连接到一个给定的端口和主机。 Ruby的TCPSocket类提供open函数打开一个套接字。

TCPSocket.open(hosname, port ) 打开一个 TCP 链接到 hostname 在端口 port.

一旦有一个套接字打开,就可以读它像任何IO对象一样。完成后记得要关闭它,因为就像需要关闭一个文件。

下面的代码是一个非常简单的客户端连接到一个给定的主机和端口,从套接字读取任何可用的数据,然后退出:


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

一个简单的服务器:

要写入互联网服务器,我们使用 TCPServer 类。 TCPServer 对象是一个工厂来创建 TCPSocket对象。

现在调用TCPServer.open(hostname, port 函数指定一个端口为您服务,并创建一个 TCPServer 对象。

接下来,调用accept方法返回 TCPServer 对象。此方法将等待客户端连接到指定的端口,然后返回一个表示连接到该客户端的TCPSocket对象。


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
}

现在运行在后台服务器,然后运行上面的客户端看到的结果。

多客户端TCP服务器:

大多数Internet上的服务器被设计来处理在任何一个时间大量的客户请求。

Ruby的 Thread 类可以轻松创建多线程服务器。接受请求,并立即创建一个新的执行线程来处理连接,同时允许主程序等待更多的连接:


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
}

在这个例子中有固定循环,并当server.accept作出响应并立即创建并启动一个新的线程来处理连接,使用连接对象传递到线程。主程序紧接循环返回,并等待新的连接。

这种方式意味着使用Ruby线程代码是可移植的以同样的方式将运行在Linux,OS X和Windows。

一个微小的Web浏览器:

我们可以使用套接字库实现任何互联网协议。例如,代码中获取内容的网页:


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.0rnrn"

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

要实现类似的web客户端,可以使用一个预构建库,如 Net::HTTP 与 HTTP 一起工作。下面是代码,这是否就相当于之前的代码:


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

请检查类似的库,FTP,SMTP,POP,IMAP协议。

进一步阅读:

我们已经快速入门Socket编程。这是一个大课题,因此建议通过以下链接找到更多的细节 Ruby Socket类库和类方法 

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务