2011-12-26 114 views
0

当我运行我的EventMachine测试代码时,发现有太多“TIME_WAIT”连接。这是个问题吗?为什么在使用EventMachine时有很多“TIME_WAIT”连接?

 
run netstat -anp | grep 8080 

    tcp  0  0 0.0.0.0:8080   0.0.0.0:*    LISTEN  13012/ruby  
    tcp  0  0 127.0.0.1:38701   127.0.0.1:8080   TIME_WAIT -    
    tcp  0  0 127.0.0.1:38706   127.0.0.1:8080   TIME_WAIT -    
    tcp  0  0 127.0.0.1:38709   127.0.0.1:8080   TIME_WAIT -    
    tcp  0  0 127.0.0.1:38708   127.0.0.1:8080   TIME_WAIT -    
    tcp  0  0 127.0.0.1:38699   127.0.0.1:8080   TIME_WAIT -    
    tcp  0  0 127.0.0.1:38700   127.0.0.1:8080   TIME_WAIT -    
    tcp  0  0 127.0.0.1:38707   127.0.0.1:8080   TIME_WAIT -    
    tcp  0  0 127.0.0.1:38705   127.0.0.1:8080   TIME_WAIT -    
    tcp  0  0 127.0.0.1:38702   127.0.0.1:8080   TIME_WAIT -    
    tcp  0  0 127.0.0.1:38703   127.0.0.1:8080   TIME_WAIT -    
    tcp  0  0 127.0.0.1:38704   127.0.0.1:8080   TIME_WAIT - 

我的测试客户端代码:

require 'rubygems' 
require 'benchmark' 
require 'socket' 
require 'logger' 
Benchmark.bm do |x| 
    logger = Logger.new('test.log', 10, 1024000) 
    logger.datetime_format = "%Y-%m-%d %H:%M:%S" 
    logger.info "----------------------------------" 
    x.report("times:") do 
    for i in 0..20 
     sleep 0.1 
     Thread.new do 
     TCPSocket.open "127.0.0.1", 8080 do |s| 
        s.send "#{i}", 0 
      if result = s.recv(100) 
      logger.info result 
      end 
     end 
     end 
    end 
    end 
end 

我的测试服务器的代码是:

require 'rubygems' 
require 'benchmark' 
require 'eventmachine' 
class Handler < EventMachine::Connection 
    def initialize(*args) 
    super 
    end 

    def receive_data(data) 
    puts "------------------------" 
    @reply = data 
    @state = :processing 
    EventMachine.defer(method(:do_something), method(:callback)) 
    rescue Exception => ex 
    LOGGER.error "#{ex.class}: #{ex.message}\n#{ex.backtrace.join("\n")}" 
    end 

    def do_something 
    #simulate a long running request 
    a = [] 
    for i in 1..3000 
     a << rand(3000) 
     a.sort! 
    end 
    return @reply 
    end 

    def callback(msg) 
    self.send_data msg 
    @state = :closing 
    end 

    def unbind 
    close_connection_after_writing #unless @state == :processing 
    end 

end 

EventMachine::run { 
    EventMachine.epoll 
    EventMachine::start_server("0.0.0.0", 8080, Handler) 
    puts "Listening..." 
} 
+0

定义'太多'。 – EJP 2011-12-26 21:33:31

回答

1

TIME_WAIT状态持续了两分钟,在TCP提供了极为重要的连接安全性。这不是问题,它是一个解决方案。

+0

这可能是一个令人难以置信的忙碌和超载机器的问题,但是,希望我们大多数人不会因为负载平衡器和智能主机设计而遇到这种情况。 – 2011-12-26 21:43:37

+0

@theTinMan可能是一个问题如何? netstat中的行太多了? – EJP 2013-06-25 21:59:15