\$\begingroup\$
\$\endgroup\$
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 &
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
You shouldn't read from the client one byte at a time. Call client.gets
to take a line at a time.
answered Aug 28, 2013 at 8:00
-
\$\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– Kokizzu2013年08月29日 02:18:02 +00:00Commented Aug 29, 2013 at 2:18
lang-rb