Question

I have been reading examples online about Ruby's TCPSocket and TCPServer, but I still don't know and can't find what's the best practice for this. If you have a running TCPServer, and you want to keep the socket open across multiple connections/clients, who should be responsible in keeping them open, the server or the clients?

Let's say that you have a TCPServer running:

server = TCPServer.new(8000)
loop do
  client = server.accept
  while line = client.gets
    # process data from client
  end
  client.puts "Response from server"
  client.close  # should server close the socket?
end

And Client:

socket = TCPSocket.new 'localhost', 8000
while line = socket.gets
  # process data from server
end
socket.close # should client close the socket here?

All of the examples I have seen have the socket.close at the end, which I would assume is not what I want as that would close the connection. Server and clients should maintain open connection as they will need to send data back and forth.

PS: I'm pretty a noob on networking, so just kindly let me know if my question sounds completely dumb.

Was it helpful?

Solution

The server is usually responsible for keeping the connections open because the client (being the one connecting to the server) can break the connection at anytime.

Servers are usually in charge of everything that the client doesn't care about. A video game doesn't really care about the connection to the server as long as it's there. It just wants its data so it can keep running.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top