在Ruby中,你可以使用多种库来进行网络传输。以下是一些常用的库和方法:
Socket
库进行TCP通信:require 'socket'
# 创建一个TCP客户端
client = Socket.new(:INET, :STREAM)
client.connect('example.com', 80)
# 向服务器发送HTTP请求
request = "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"
client.send(request, 0)
# 接收服务器的响应
response = ''
while buffer = client.recv(4096)
response += buffer
end
# 关闭连接
client.close
puts response
Net::HTTP
库进行HTTP通信:require 'net/http'
require 'uri'
url = URI('http://example.com')
response = Net::HTTP.get(url)
puts response
Net::SSH
库进行SSH通信:require 'net/ssh'
ssh = Net::SSH.start('example.com', 'username', :password => 'password')
output = ssh.exec!("ls")
puts output
ssh.close
OpenSSL
库进行SSL/TLS通信:require 'openssl'
require 'net/http'
require 'uri'
url = URI('https://example.com')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
response = http.get(url.request_uri)
puts response
这些库和方法可以帮助你在Ruby中进行网络传输。你可以根据自己的需求选择合适的库进行操作。