2016-01-20 56 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