我正在读取TCP套接字上的输入行,类似于:
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()挂起.
我该如何解决这个问题?是否有必要进行非阻塞或定时I/O?
您可以使用select来查看是否可以安全地从套接字获取,请参阅以下使用此技术实现TCPServer.
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
这里是一个试图打破服务器的客户端:
require 'socket' host, port = 'localhost', 7000 TCPSocket.open(host, port) do |socket| socket.puts "Hey there" socket.write 'he' socket.flush socket.close end