在Ruby中,你可以使用多種庫來進(jìn)行網(wǎng)絡(luò)傳輸。以下是一些常用的庫和方法:
Socket
庫進(jìn)行TCP通信:require 'socket'
# 創(chuàng)建一個(gè)TCP客戶端
client = Socket.new(:INET, :STREAM)
client.connect('example.com', 80)
# 向服務(wù)器發(fā)送HTTP請求
request = "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"
client.send(request, 0)
# 接收服務(wù)器的響應(yīng)
response = ''
while buffer = client.recv(4096)
response += buffer
end
# 關(guān)閉連接
client.close
puts response
Net::HTTP
庫進(jìn)行HTTP通信:require 'net/http'
require 'uri'
url = URI('http://example.com')
response = Net::HTTP.get(url)
puts response
Net::SSH
庫進(jìn)行SSH通信:require 'net/ssh'
ssh = Net::SSH.start('example.com', 'username', :password => 'password')
output = ssh.exec!("ls")
puts output
ssh.close
OpenSSL
庫進(jìn)行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中進(jìn)行網(wǎng)絡(luò)傳輸。你可以根據(jù)自己的需求選擇合適的庫進(jìn)行操作。