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

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

这篇教程介绍 Ruby Socket编程概念及讲解一个简单的实例。
什么是Sockets"2015513102934767.jpg (592×667)" src="/UploadFiles/2021-04-08/2015513102934767.jpg">

 一个简单的客户端:

在这里,我们将编写一个非常简单的客户端程序,这将打开一个连接到一个给定的端口和主机。 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.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

要实现类似的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协议。

 

标签:
Ruby

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
内蒙古资源网 Copyright www.nmgbbs.com

评论“Ruby中的Socket编程简单入门”

暂无“Ruby中的Socket编程简单入门”评论...

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。