Timo Küfner
Timo Küfner

Reputation: 85

Check if socket-client is still connected

I want to implement a while-loop that runs as long as a Client is connected at my socket. It's gonna be Thread based so i want to make shure that the Thread gets closed once the Client disconnected.

  1. question: How do I check if the Client is still connected to my socket?

  2. question: Is the Thread already getting closed when connection closes if I startet it like this: Thread.start(socket.accept) do |client| ...

Upvotes: 3

Views: 7007

Answers (3)

Spirit of Stallman
Spirit of Stallman

Reputation: 43

server = TCPServer.open 12345

loop {
  Thread.start(server.accept) do |client|
    ...
    puts "client is offline!" if client.closed?
    ...
    client.close
  end
}

You may check "closed?" in "client".

Upvotes: 1

kanna
kanna

Reputation: 366

Check this out,

require 'socket'                
th=[]
server = TCPServer.open(2000)

loop do
  Thread.start(server.accept) do |client|
    client.puts "server started.."

    # Something

    th = Thread.list
    th.each do |t|
      if t.status == "sleep" # checks all client status
        f = t.kill           # kills thread if client is disconnected
      end
    end
  end
end

You may kill the thread or you can store the IP addres of clients using that thread in an array and make a compare with that for exact client.(like, t.addr)

Upvotes: 2

Manuel Alves
Manuel Alves

Reputation: 4013

I don't have experience programming ruby. If it was .Net, what you pretend is not possible without some kind of keep-alive protocol. If the server does not get data from client after x seconds it assumes the client disconnected. The client must have a timer to send something to the server when not communicating.

Upvotes: 1

Related Questions