首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Ruby Socket 程式設計入門:TCP 客戶端/伺服器、多線程與簡易網頁瀏覽器

     編輯:更多程式設計知識

Socket 基礎概念

Socket 是雙向通訊端點,支援進程間通訊(同機或跨機)。Ruby 提供底層 TCPSocket/TCPServer 及高階 Net::HTTP 等函式庫。

簡易 TCP 客戶端

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

簡易 TCP 伺服器

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

簡易網頁瀏覽器 (原始 Socket)

require 'socket'
host = 'www.tutorialspoint.com'
port = 80
path = '/index.htm'
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.tutorialspoint.com'
path = '/index.htm'
http = Net::HTTP.new(host)
headers, body = http.get(path)
if headers.code == "200"
  print body
else
  puts "#{headers.code} #{headers.message}"
end

同類函式庫

  • Net::FTP、Net::SMTP、Net::POP、Net::IMAP 分別對應 FTP、SMTP、POP3、IMAP 協定。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved