0

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.

garbagecollector
  • 3,731
  • 5
  • 32
  • 44

1 Answers1

1

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.

benbot
  • 1,217
  • 1
  • 12
  • 28
  • What happens if client closes the connection and reconnect (from/to the same port on the client and server) is it going to be the same connection? – garbagecollector Mar 12 '14 at 01:52
  • @DumpHole If the client disconnects (intentionally) no. If their internet drops then the packets that are being sent back and forth are being dropped. If your client suddenly comes back online and the server didn't think the client timed out, it should be the same connection. – benbot Mar 12 '14 at 18:52