2014-03-28 19 views
0

事情是我在Ruby編程中非常初學,在理解Ruby的行爲方面遇到一些麻煩。使用套接字時Ruby腳本的不尋常行爲

下面是代碼:

require 'socket' 

server = TCPServer.new 2000 
loop do 
    Thread.start(server.accept) do |client| 

    puts 'Client connected: ' + client.gets 

    line = "-1" 

    while (line != "/close ") 
     line = client.gets(); 
     puts line 
    end 

    puts 'client closed' 
    client.close 
    end 
end 

正如你看到的,這是一個簡單的socket服務器等待一些輸入信息。 問題是,當它得到「/ close」時,它退出while循環,但永遠不會去 puts 'client closed'client.close。那麼爲什麼會這樣,或者我做錯了什麼?

回答

1

我懷疑如果將puts line更改爲puts line.inspect,您會看到問題。


找到了嗎? gets按行讀取,其中包括行終止\n,所以沒有行會得到永遠等於"/close "。例如,將比較結果改爲使用line.strip即可。

+0

非常感謝你,''line.strip''並從''/ close「中移除」「之後,所有按預期方式工作! –