2017-12-03 193 views
1

我是Ruby插座中的新手。我在服務器項目,我坐了起來插座的服務器如下:紅寶石插座 - 運行在socker上的方法

require 'socket'    
server = TCPServer.open(2000)  
loop {       
    Thread.start(server.accept) do |client| 
    client.puts(Time.now.ctime) 
    client.puts "Closing the connection. Bye!" 
    client.close     
end 

我想從客戶端運行我的方法之一,在我的項目:

require 'socket'  

hostname = 'localhost' 
port = 2000 

s = TCPSocket.open(hostname, port) 

while line = s.gets  
    puts line.chop  
    puts "hey" 

    # call helloWorldMethod() 
end 

s.close     

回答

0
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 

我相信您的解決方案是在​​

,我發現這個文檔中關於ruby socket programming

微型網頁瀏覽器

我們可以使用套接字庫來實現任何Internet協議。這裏,例如,是抓取網頁

取決於你的路由你可能要調整URL的內容的代碼,它chould是www.yourwebsite.com/users

require 'socket' 

host = 'www.tutorialspoint.com'  # The web server 
port = 80       # Default HTTP port 
path = "/index.htm"     # The file we want 

這是HTTP請求我們發送獲取文件

,您可以在HTTP postput要求

改變你的要求
request = "GET #{path} HTTP/1.0\r\n\r\n" 

socket = TCPSocket.open(host,port) # Connect to server 
socket.print(request)    # Send request 
response = socket.read    # Read complete response 
# Split response at first blank line into headers and body 
headers,body = response.split("\r\n\r\n", 2) 
print body       # And display it 

要實現類似的Web客戶端,您可以使用像Net :: HTTP這樣的預建庫來處理HTTP。以下是代碼,代碼相當於以前的代碼 -

require 'net/http'     # The library we need 
host = 'www.tutorialspoint.com'  # The web server 
path = '/index.htm'     # The file we want 

http = Net::HTTP.new(host)   # Create a connection 
headers, body = http.get(path)  # Request the file 
if headers.code == "200"   # Check the status code 
    print body       
else         
    puts "#{headers.code} #{headers.message}" 
end