现在的位置: 首页 > 综合 > 正文

Ruby网络编程

2018年04月19日 ⁄ 综合 ⁄ 共 809字 ⁄ 字号 评论关闭

Ruby支持很多网络协议,不管是高层的还是底层的。ruby提供了一些基本类,让你可以使用TCP,UDP,SOCKS等很多协议交互,而不必拘泥在网络层。这些类也提供了辅助类,让你可以轻松的对服务器进行读写。这个例子利用finger协议查询用户oracle的信息:


require 'socket'
client = TCPSocket.open('localhost', 'finger')
client.send("oracle\n", 0) # 0 means standard packet
puts client.readlines
client.close

 
结果: Login: oracle Name: Oracle installation
Directory: /home/oracle Shell: /bin/bash
Never logged in.
No Mail.
No Plan.

 


对于高层,lib/net里面提供了一些与应用层协议(FTP,HTTP,POP,SMTP,TELNET)等交互的库模块。比如,下面的例子列出了Pragmatic Programmer主页里的图像。  

require 'net/http'

h = Net::HTTP.new('www.pragmaticprogrammer.com', 80)
resp, data = h.get('/index.html', nil)
if resp.message == "OK"
  data.scan(/<img src="(.*?)"/) { |x| puts x }
end

 
produces: images/title_main.gif
images/dot.gif
images/dot.gif
images/dot.gif
images/aafounders_70.jpg
images/pp_cover_thumb.png
images/ruby_cover_thumb.png
images/dot.gif
images/dot.gif

 

抱歉!评论已关闭.