2012-06-03 39 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