在 get() 中从 Ruby 中损坏的 TCP 套接字中恢复 [英] Recovering from a broken TCP socket in Ruby when in gets()
本文介绍了在 get() 中从 Ruby 中损坏的 TCP 套接字中恢复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在读取 TCP 套接字上的输入行,类似于:
I'm reading lines of input on a TCP socket, similar to this:
class Bla
def getcmd
@sock.gets unless @sock.closed?
end
def start
srv = TCPServer.new(5000)
@sock = srv.accept
while ! @sock.closed?
ans = getcmd
end
end
end
如果端点在 getline() 运行时终止连接,则 gets() 挂起.
If the endpoint terminates the connection while getline() is running then gets() hangs.
我该如何解决这个问题?是否有必要做非阻塞或定时 I/O?
How can I work around this? Is it necessary to do non-blocking or timed I/O?
推荐答案
您可以使用 select 来查看是否可以安全地从套接字获取,请参阅以下使用此技术实现的 TCPServer.
You can use select to see whether you can safely gets from the socket, see following implementation of a TCPServer using this technique.
require 'socket'
host, port = 'localhost', 7000
TCPServer.open(host, port) do |server|
while client = server.accept
readfds = true
got = nil
begin
readfds, writefds, exceptfds = select([client], nil, nil, 0.1)
p :r => readfds, :w => writefds, :e => exceptfds
if readfds
got = client.gets
p got
end
end while got
end
end
这里是一个试图破坏服务器的客户端:
And here a client that tries to break the server:
require 'socket'
host, port = 'localhost', 7000
TCPSocket.open(host, port) do |socket|
socket.puts "Hey there"
socket.write 'he'
socket.flush
socket.close
end
这篇关于在 get() 中从 Ruby 中损坏的 TCP 套接字中恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文