2014-09-21 78 views
0

我有一個TCP服務器,我在紅寶石,服務器似乎工作,我可以看到,兩個或更多的客戶端可以連接並由服務器提供服務,但他們有時會卡住(如在需要等待其他客戶端斷開連接或只是無響應),通常在「pass_ok」位之後,當僅連接一個客戶端時,我不會看到這個問題。Ruby中的多線程

這裏是我的代碼:

def self.main_server 
    begin 
     server = TCPServer.open(@port) 
    rescue Exception => e 
     CoreLogging.syslog_error("Cant start server: #{e}") 
    end 
    @main_pid = Process.pid 
    # Main Loop 
    Thread.abort_on_exception = true 
    while true 
     Thread.fork(server.accept) do |client| 
     @client = client 
     sock_domain, remote_port, remote_hostname, remote_ip = @client.peeraddr # Get some info on the incoming connection 
     CoreLogging.syslog_error("Got new connection from #{@client.peeraddr[3]} Handeled by Thread: #{Thread.current}") # Log incoming connection 
     @client.puts "Please enter password: " # Password testing (later will be from a config file or DB) 
     action = @client.gets(4096).chomp # get client password response 'chomp' is super important 
     if action == @password 
      # what to do when password is right 
      pass_ok 
      Thread.exit 
     else 
      # what to do when password is wrong 
      pass_fail 
      Thread.exit 
     end 
     end 

     begin 
     CoreLogging.syslog_error("Thread Ended (SOFT)") 
     rescue Exception => e 
     CoreLogging.syslog_error("Thread was killed (HARD)") 
     end 
    end 
    end 

回答

0

我會離開這裏以供將來參考,並希望有人在近距離的情況會發現它是有用的。

問題是全局@client變量,它覆蓋每個新線程,然後繼承到線程內部的子類。

使用本地客戶端變量(沒有'@')讓它按假設工作。