在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中進行網絡傳輸。你可以根據自己的需求選擇合適的庫進行操作。