Ruby 提供兩層級網路存取:低階 Socket 類別實作 TCP/UDP,高階函式庫如 Net::HTTP、Net::FTP 封裝應用層協定。本文介紹 TCPSocket、TCPServer 基礎用法、多執行緒 Server 架構、簡易 Web Client 實作。

require 'socket'
host = 'localhost'
port = 2000
s = TCPSocket.open(host, port)
while line = s.gets
puts line.chop
end
s.close
require 'socket'
server = TCPServer.open(2000)
loop do
client = server.accept
client.puts Time.now.ctime
client.puts "Closing the connection. Bye!"
client.close
end
require 'socket'
server = TCPServer.open(2000)
loop do
Thread.start(server.accept) do |client|
client.puts Time.now.ctime
client.puts "Closing the connection. Bye!"
client.close
end
end
require 'socket'
host = 'www.example.com'
port = 80
path = "/index.html"
request = "GET #{path} HTTP/1.0\r\n\r\n"
socket = TCPSocket.open(host, port)
socket.print(request)
response = socket.read
headers, body = response.split("\r\n\r\n", 2)
print body
require 'net/http'
host = 'www.example.com'
path = '/index.html'
http = Net::HTTP.new(host)
headers, body = http.get(path)
if headers.code == "200"
print body
else
puts "#{headers.code} #{headers.message}"
end
建議: 實務上優先使用高階函式庫(Net::HTTP, HTTParty, Faraday),僅在需要自訂協定時使用低階 Socket。