2016-01-20 57 views
1

我想通過Ruby在我的局域網上生成本地服務器(如localhost/8000)(我不喜歡創建word)我研究了互聯網,但我無法做到。 我的目標是在本地服務器上顯示html頁面,由Ruby使用。 我該怎麼做?如何在Ruby中生成本地服務器

require 'socket' 

我使用斯坦達特圖書館插座但是當我刷新頁面提示錯誤。

require 'socket' 
server = TCPServer.new('localhost', 2345) 
loop do 
    socket = server.accept 
    request = socket.gets 
    STDERR.puts request 
    response = "Hello World!\n" 
    socket.print "HTTP/1.1 200 OK\r\n" + 
      "Content-Type: text/plain\r\n" + 
      "Content-Length: #{response.bytesize}\r\n" + 
      "Connection: close\r\n" 

    socket.print "\r\n" 
    socket.print response 
    socket.close 
end 
+0

'rails s'啓動本地服務器 – brito

+0

請問您可以提供更多信息嗎? –

+0

在終端中,導航到Rails項目根文件夾,輸入'rails s'並按回車。 – brito

回答

0

你可以做

ruby -run -e httpd -- . -p 8000 

將開始在服務當前目錄(其中服務器啓動)端口8000的服務器。因此,您可以將所有的HTML頁面放在一個文件夾中,並從那裏啓動服務器。

3

其他人認爲你只是想開始一個Web服務器,也許你的問題是如何紅寶石編寫一個Web服務器。 這是紅寶石web服務器中good introduction,它包含一個例子展示瞭如何構建一個樣品的http服務器,引用在這裏爲你:

require 'socket' 
server = TCPServer.new 80 

loop do 
    # step 1) accept incoming connection 
    socket = server.accept 

    # step 2) print the request headers (separated by a blank line e.g. \r\n) 
    puts line = socket.readline until line == "\r\n" 

    # step 3) send response 

    html = "<html>\r\n"+ 
     "<h1>Hello, World!</h1>\r\n"+ 
     "</html>" 

    socket.write "HTTP/1.1 200 OK\r\n" + 
       "Content-Type: text/html; charset=utf-8\r\n" + 
       "Content-Length: #{html.bytesize}\r\n" 

    socket.write "\r\n" # write a blank line to separate headers from the html doc 
    socket.write html # write out the html doc 

    # step 4) close the socket, terminating the connection 
    socket.close 
end 

運行紅寶石this_file.rb啓動它,並用GET方法測試。

+1

這絕對應該是被接受的答案。它看起來像OP只是使用紅寶石自己介紹網絡的東西。 Rails是一個完全不同的野獸,其他答案/評論等同於使用rails的ruby有點令人不安。 – Antiokus

-1

所有你需要做的就是打開您的控制檯,然後輸入rails server

如果你想指定你可以做端口rails server -p xxxx