Recovering from a broken TCP socket in Ruby when in gets() -


i'm reading lines of input on tcp socket, similar 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 

if endpoint terminates connection while getline() running gets() hangs.

how can work around this? necessary non-blocking or timed i/o?

you can use select see whether can safely gets socket, see following implementation of tcpserver using technique.

require 'socket'  host, port = 'localhost', 7000  tcpserver.open(host, port) |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 client tries break server:

require 'socket'  host, port = 'localhost', 7000  tcpsocket.open(host, port) |socket|   socket.puts "hey there"   socket.write 'he'   socket.flush   socket.close end 

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -