1
\$\begingroup\$

Server:

require 'socket'
require 'time'
require 'ap'

server = TCPServer.open(1026)

def process_the_request req, client # not important, disk-related process
  sleep 2
  req.to_s + ' ' + client.peeraddr[3].to_s + ' ' + Time.now.to_s
end

loop do

  Thread.start(server.accept) do |client|

    request = ''
    ch = ''

    begin 

      ch = client.getc
      print ch

      if (ch.nil? or ch.ord == 13 or ch.ord == 10)

        if request.length < 1
          break if client.eof?
          next
        end

        ap "request: " + request
        response = process_the_request request, client
        ap "response: " + response
        client.puts response
        request = ''
        break if client.eof?

      else
        request += ch
      end


    end while true

    #ap "thread closed" 
    client.close

  end # Thread

end # loop

Client:

nn='nc 127.0.0.1 1026'
echo -n '1' | $nn &
echo '2' | $nn &
echo -n '3' | $nn &
echo '4
5
6
7' | $nn &
\$\endgroup\$
1
\$\begingroup\$

You shouldn't read from the client one byte at a time. Call client.gets to take a line at a time.

\$\endgroup\$
  • \$\begingroup\$ somehow client.gets not working when client breaks (e.g. when they forgot to send \n on the last line), i ended up running too many unfinished thread \$\endgroup\$ – Kokizzu Aug 29 '13 at 2:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.