我一直在网上阅读关于Ruby的TCPSocket和TCPServer的例子,但我仍然不知道,并且找不到最佳实践。如果你有一个正在运行的TCPServer,并且你想让多个连接/客户端保持套接字打开,谁应该负责保持它们,服务器或客户端?
假设您正在运行TCPServer:
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
和客户:
socket = TCPSocket.new 'localhost', 8000
while line = socket.gets
# process data from server
end
socket.close # should client close the socket here?
我见过的所有例子都有socket.close
,我认为这不是我想要的,因为它会关闭连接。服务器和客户端应保持开放连接,因为它们需要来回发送数据。
答案 0 :(得分:1)
服务器通常负责保持连接打开,因为客户端(连接到服务器的客户端)可以随时中断连接。
服务器通常负责客户不关心的所有事情。视频游戏并不真正关心与服务器的连接,只要它在那里。它只是想要它的数据,所以它可以继续运行。