简体   繁体   中英

Ruby: connection timeout detection for a TCPServer

been trying to understand how to implement a timeout detection to a ruby TCP server of mine. Mainly because sometimes clients with instable internet lose connection and i need my server to detect it.

The idea is to teach my server to detect when a connection had been silent for longer than 30 seconds and abort it. I've been trying to use timeout, but it terminates the program, so i need to use something like a simple timer that will just return an integer of seconds passed since the activation of the said timer.

Is there an already made solution for that? Sorry if it is a stupid question, it's just that googling it led me nowhere. ps: using ruby 1.8 here.

The 'Time' object can report the number of seconds past by comparing it to previously created instances. Consider:

require 'time'

t0 = Time.now
sleep(2)
t1 = Time.now
t1.to_f - t0.to_f # => 2.00059294700623

So by creating a "last transmission" time object then checking its difference from "now" you can determine the number of seconds passed and act accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM