2012-06-03 40 views
0

我正在嘗試將此從Ruby轉換爲Python。 Ruby代碼:Python套接字超時和刷新

def read_byte 
    begin 
     Timeout.timeout(0.5) do 
      b = socket.read 1 
     end 
    rescue Timeout::Error => e 
     socket.write("\n") 
     socket.flush 
     retry 
    end 
end 

def socket 
    @socket ||= TCPSocket.open @host, @port 
rescue SocketError 
    # TODO: raise a specific error 
    raise "Unable to open connection to #{@host} with given parameters" 
end 

我這裏指的問題是與

socket.flush

我不能找到一種方法做齊平。我可以用其他方式做到這一點? 我寫了這個。 Python代碼:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect((self.host, self.port)) 
s.settimeout(0.5) 
while True: 
    try: 
     print s.recv(1) 
    except socket.timeout: 
     s.sendall("\n") 
+1

你會期望沖洗套接字來執行'sendall()'dosen't已經做了什麼? – kindall

+0

流是有點掛在我的代碼。它正在使用Ruby代碼。 –

回答

0

我懷疑沖洗插座會有所作爲,但在這裏是一種方法,首先創建一個類似文件的對象「刷新」插座。

def flush_socket(s): 
    f = s.makefile() 
    f.flush() 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect((self.host, self.port)) 
s.settimeout(0.5) 
while True: 
    try: 
     print s.recv(1) 
    except socket.timeout: 
     s.sendall("\n") 
     flush_socket(s) 
+0

它仍然沒有像Ruby代碼一樣接收。也許這是ruby代碼的另一部分或某事。 –

0

的流掛有點我的代碼。

當然是因爲它是一個無限循環,除非發生除socket.timeout以外的其他異常。

也許是Ruby代碼

它必須是另一部分...檢查紅寶石環路,其中read_byte被稱爲和比較,爲你的Python while True

+0

兩年前我沒有在這方面做過工作。如果你感興趣,你可以看到更新的[Ruby代碼](https://github.com/gareth/live_f1-core)和我的[Python代碼](https://github.com/dadoeyad/live-f1- py) –

+0

* live_f1-core/lib/live_f1/source/live.rb *中更新後的Ruby代碼_' read_bytes num'嘗試只讀'num'字節,與Python'while True'時的無限多個字節相比。 – Armali