Ruby 'net/http' 怎么发长连接请求

tablecell · 2019年10月25日 · 最后由 tablecell 回复于 2019年10月27日 · 4958 次阅读

测试代码
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 都是不同的 怎么样让某个客户端的多次请求 让一个线程内处理

1 楼 已删除
HTTP.persistent "http://www.baidu.com" do |http|
    // 使用http变量请求
end
HDJ 回复

uninitialized constant HTTP (NameError) 这是 net/http 的方法 吗

HTTP.persistent "http://www.baidu.com" do |http|
    // 使用http变量请求
end
tablecell 回复

😂 额。。这是 http 包的,不是 net/http 包。抱歉。我都没怎么用过 net/http 包。我大多数都是用的这个https://github.com/httprb/http

怎么样让某个客户端的多次请求 让一个线程内处理 用 nio,nio https://ruby-china.org/topics/38404 或者看 AnctionCable 的源码。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号