M
M
Marat Amerov2015-06-02 22:01:42
ruby
Marat Amerov, 2015-06-02 22:01:42

How to properly implement a web server with keep-alive connections?

Hey!

Server example in Ruby:

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 # если раскомментировать  - все ок.
      end
    end
  end
end

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


set to `sleep for 3 seconds`. if you do not wait for execution and refresh the page, then in this case it does not reach the execution of `@server.accept`, but if you close the connection, then everything is ok.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
CAMOKPYT, 2015-06-02
@CAMOKPYT

EventMachine, Rack

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question