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 Answer 1

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\$
1
  • \$\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\$ Commented Aug 29, 2013 at 2:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.