Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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 &
share|improve this question

1 Answer 1

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

share|improve this answer
    
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 –  Kokizzu Aug 29 '13 at 2:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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