2017-12-03 20 views
1

Rubyソケットが新しくなっています。私は、サーバーでプロジェクトを持っていると私は、次のようにサーバーにソケットを起き上がっ:Rubyソケット - socker上でメソッドを実行

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 

I:

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 

が、私はクライアントからの私のプロジェクトで私の方法のいずれかを実行したいと思いますあなたのソリューションは、私がこのドキュメントに関するruby socket programming

を見つけ​​

であると信じて

小さなウェブブラウザ

私はソケットライブラリを使ってインターネットプロトコルを実装することができます。ここでは、たとえば、あなたがURLを適応することができますあなたのルーティングに応じて、Webページ

のコンテンツを取得するコードがあり、それはこれがある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 

ことchould私たちはあなたがHTTP postput要求

にあなたの要求を変更することができ、ファイル

をフェッチするために送るHTTPリクエスト

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クライアントを実装するには、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