我想用Ruby在我的局域网上生成一个本地服务器(比如localhost/8000),我研究了İ网络,但是我做不到。我的目标是通过Ruby在本地服务器中显示html页面。我怎么能做到呢?
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发布于 2016-01-21 18:53:02
你可以
ruby -run -e httpd -- . -p 8000它将在端口8000处启动服务器,以服务于当前目录(启动服务器的地方)。因此,您可以将所有HTML页面放在一个文件夹中,然后从那里启动服务器。
发布于 2016-01-20 23:46:39
其他人认为你只是想用启动一个web服务器,也许你的问题是如何用ruby编写一个web服务器。这是一个在ruby服务器上的很好的介绍,它包含一个示例,演示如何构建一个示例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首先运行ruby this_file.rb,然后使用get方法进行测试。
发布于 2016-01-21 04:47:41
你可以用机架来做这件事,http://rack.github.io/,rails也是以机架为基础的。
https://stackoverflow.com/questions/34912608
复制相似问题