萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Ruby Socket 程式設計入門:TCP Client/Server、多執行緒 Server、微型 Web Client

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

基本術語

Socket 術語

簡易 TCP Client

require 'socket'
host = 'localhost'
port = 2000
s = TCPSocket.open(host, port)
while line = s.gets
  puts line.chop
end
s.close

簡易 TCP Server

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

多執行緒 TCP Server

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

微型 Web Client(Socket 版)

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

高階 Net::HTTP 版

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。

copyright © 萬盛學電腦網 all rights reserved