测试代码
server.rb
require 'socket'
server = TCPServer.open('127.0.0.1', 8080)
loop {
Thread.start(server.accept) do | client |
loop{
#puts client
lines = []
while line = client.gets and line !~ /^\s*$/
lines << line.chomp
end
puts Thread.current
puts lines
#resp = lines.join("\n")
resp="aaabbb123"
headers = ["HTTP/1.0 200 OK",
"Date: tue, 14 dec 2019 10:48:45 GMT",
"Server: ruby mtserver",
"Content-Type: text/html; charset=utf-8",
"Content-Length: #{resp.length}\r\n\r\n"].join("\r\n")
puts headers.size+resp.size
client.puts headers #send to the client
client.puts resp
}
end
}
client.rb
require 'net/http'
uri = URI('http://localhost:8080/')
res = Net::HTTP.start(uri.hostname, uri.port) {|http|
loop do
puts "\n\n------------"
http.request_get('/') {| resp |
resp.read_body do |str|
print str
end
}
sleep(2)
end
}
虽然能收发信息,但是 服务端每次显示的 Thread.current 都是不同的 怎么样让某个客户端的多次请求 让一个线程内处理