您可以使用 ensure 一旦写入失败或连接已关闭或出现问题,确保您的流关闭:
ensure
def your_action response.headers['Content-Type'] = 'text/event-stream' begin # Do your writing here: response.stream.write("data: ...\n\n") rescue IOError # When the client disconnects, writing will fail, throwing an IOError ensure response.stream.close end end