如何在 Ruby 中生成本地服务器

ser*_*eri 1 html ruby ruby-on-rails local server

我想通过 Ruby 在我的 LAN 上生成(我不喜欢创建单词)本地服务器(如 localhost/8000),我研究了 ? 互联网,但我无法做到。我的目标是在本地服务器中显示 html 页面,使用 Ruby。我怎样才能做到?

require 'socket'
Run Code Online (Sandbox Code Playgroud)

我在标准库中使用套接字,但在刷新页面时出现错误。

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
Run Code Online (Sandbox Code Playgroud)

Hai*_*Cao 5

其他人认为你只是想启动一个 web 服务器,也许你的问题是如何用 ruby​​ 编写一个 web 服务器。这是一个关于 ruby​​ web 服务器的很好的介绍,它包含一个示例,展示了如何构建示例 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
Run Code Online (Sandbox Code Playgroud)

通过运行 ruby​​ this_file.rb 启动它,并使用 get 方法进行测试。


Cri*_*nça 5

你可以做

ruby -run -e httpd -- . -p 8000
Run Code Online (Sandbox Code Playgroud)

这将在端口 8000 启动服务器,为当前目录(服务器启动的地方)提供服务。因此,您可以将所有 HTML 页面放在一个文件夹中并从那里启动服务器。