Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: What is the best way to constantly communicate with multiple sockets?  (Read 929 times)

0 Members and 1 Guest are viewing this topic.

BananaBro_Chaos

  • Newbie
  • *
  • Posts: 9
    • View Profile
I am writing a server that can connect with various clients to send and receive information. I am using TCP Sockets. Currently, I am faced with a decision. I can either keep every socket connection from the clients open until they disconnect, or I only connect with the client every time there is a prompt from the client.

The former makes it easy for the server to detect a prompt from any socket (if I'm not mistaken, a Socket Selector can achieve that); however, sockets are non-copyable, meaning I can't just store them in a vector. I can store pointers in the vector, but if the actual socket is destroyed, the pointer will be useless. This is why I am inclined to try the latter option; however, I am unsure if this is actually an efficient method of communication.

Basically, I have three questions. Firstly, which of the two methods of socket management should I use, keeping them all open or only connecting when prompted? Secondly, is there a method to store sockets, or socket pointers, in a container, like a vector, reliably? Lastly, is opening and closing a connection every time the server is prompted actually efficient?

Thank you in advance! Please inform me if my question is unclear.

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11018
    • View Profile
    • development blog
    • Email
Re: What is the best way to constantly communicate with multiple sockets?
« Reply #1 on: October 19, 2024, 10:25:57 pm »
It very much depends on your needs. If you expect a continuous communication between clients and server, it doesn't really make sense to keep closing the connection. A connection build up is kind of slow and expensive, e.g. a TCP "3-way" handshake goes from the client, to the server, to the client and to the server, at say 100ms, that's already at least 300ms lost just on the connection establishing.
But if your application rarely talks to the server, like every minute or so, then it might make sense to create a new temporary connection. Not just because it's waste of resource, but also because TCP would automatically close the connection (by default on Windows) after four minutes of no communication.

Closing a connection doesn't destroy the sf::TcpSocket instance. You'll just have to check the return value of the send/receive if it's Disconnected (or potentially Error).
You may want to store the connections in a stable container such as std::unordered_map or use a std::vector<std::unique_ptr<sf::TcpSocket>>.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/