Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Ruby编写一个简单的Web服务器_Ruby_Webserver - Fatal编程技术网

用Ruby编写一个简单的Web服务器

用Ruby编写一个简单的Web服务器,ruby,webserver,Ruby,Webserver,我想用Ruby创建一个非常简单的web服务器,用于开发目的(不,不想使用现成的解决方案) 代码如下: #!/usr/bin/ruby require 'socket' server = TCPServer.new('127.0.0.1', 8080) while connection = server.accept headers = [] length = 0 while line = connection.gets headers << line

我想用Ruby创建一个非常简单的web服务器,用于开发目的(不,不想使用现成的解决方案)

代码如下:

#!/usr/bin/ruby

require 'socket'

server = TCPServer.new('127.0.0.1', 8080)

while connection = server.accept
  headers = []
  length  = 0

  while line = connection.gets
    headers << line

    if line =~ /^Content-Length:\s+(\d+)/i
      length = $1.to_i
    end

    break if line == "\r\n"
  end

  body = connection.readpartial(length)

  IO.popen(ARGV[0], 'r+') do |script|
    script.print(headers.join + body)
    script.close_write
    connection.print script.read
  end

  connection.close
end
您知道如何改进上述代码以使其易于使用吗


版本:Ubuntu 9.10(2.6.31-20-generic)、Ruby 1.8.7(2009-06-12 patchlevel 174)[i486 linux]

使用Ruby Webrick库,您可以轻松构建Web服务器


问题似乎出在子脚本中,因为您问题中的父脚本在my box上运行(Debian Squence,Ruby 1.8.7 patchlevel 249):

我创建了虚拟子脚本bar.rb:

#!/usr/bin/ruby1.8

s = $stdin.read
$stderr.puts s
print s
然后,我运行您的脚本,将其路径传递给虚拟脚本:

$ /tmp/foo.rb /tmp/bar.rb
我用wget击中它:

$ wget localhost:8080/index
并查看虚拟脚本的输出:

GET /index HTTP/1.0^M
User-Agent: Wget/1.12 (linux-gnu)^M
Accept: */*^M
Host: localhost:8080^M
Connection: Keep-Alive^M
^M
我还看到wget收到了它发送的内容:

$ cat index
GET /index HTTP/1.0
User-Agent: Wget/1.12 (linux-gnu)
Accept: */*
Host: localhost:8080
Connection: Keep-Alive

无论我用wget点击它多少次,它都是一样的。

描述了大多数web服务器实现策略。

我尝试了您的子脚本,第一次运行时它抛出了一个错误。也许这里有一些操作系统级别的差异。好吧,我找到了问题所在。它在子脚本中:我只是打印了一个基本的HTTP响应,而您首先阅读了stdin。现在的问题是为什么有必要这么做。乔,既然你和我得到了如此不同的结果,也许你应该在你的问题中添加你的Ruby和OS版本。
$ cat index
GET /index HTTP/1.0
User-Agent: Wget/1.12 (linux-gnu)
Accept: */*
Host: localhost:8080
Connection: Keep-Alive