ruby中的web服务器和连接保持活动状态

时间:2015-06-03 12:47:25

标签: ruby web-services sockets http io

Web服务器示例:

require 'rubygems'
require 'socket'
require 'thread'

class WebServer
  LINE_TERMINATOR = "\r\n".freeze

  def initialize(host, port)
    @server = TCPServer.new(host, port)
  end

  def run
    response_body = 'Hello World!'.freeze
    response_headers = "HTTP/1.1 200 OK#{LINE_TERMINATOR}Connection: Keep-Alive#{LINE_TERMINATOR}Content-Length: #{response_body.bytesize}#{LINE_TERMINATOR}".freeze

    loop do
      Thread.new(@server.accept) do |socket|
        puts "request #{socket}"
        sleep 3
        socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
        socket.write(response_headers)
        socket.write(LINE_TERMINATOR)
        socket.write(response_body)
        # socket.close # if this line is uncommented then it's work.
      end
    end
  end
end

WebServer.new('localhost', 8888).run

如果更新浏览器而不等待循环结束,则不处理以下查询

如何处理持久套接字的incomming请求?

1 个答案:

答案 0 :(得分:0)

你需要:

  1. 保留从@server.accept电话中获得的套接字。将它们存储在一个数组中(socket_array)。
  2. 使用套接字数组上的IO.select调用来获取可以读取的套接字集:

    ready = IO.select(socket_array)
    readable = ready[0]
    
    readable.each do |socket|
        # Read from socket here
        # Do the rest of processing here
    
  3. 发送数据后请勿关闭套接字。

  4. 如果您需要更多详细信息,请发表评论 - 我可以编写更多代码。