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

Author Topic: How to reconnect a socket.  (Read 1940 times)

0 Members and 1 Guest are viewing this topic.


  • Newbie
  • *
  • Posts: 2
    • View Profile
How to reconnect a socket.
« on: October 06, 2022, 06:51:44 pm »
I'm trying my hand at a co op game and have a standalone server that also acts as a dungeon master.

If the server computer dies I want to give an in game option to 'try to reconnect' so I've assigned a key press to do this for testing.

On tab, the following function is called, basically the same function as on game start /logon. I will change this function somewhat, but I'm wondering why it doesn't connect a second time around when the server is back up. Is it related to using a socket that has previously disconnected etc. I've browsed through some of the docs but have missed it. To clarify this code works when initially connecting.


void Game::initConnection()
                bool connect = false;
        while (!connect)
                if (client.socket.connect(client.ip, 2000) == sf::Socket::Done)
                        connect = true;
                        std::cout << "Connection made\n ";
                        std::cout << "Connected to server \n " << client.socket.getRemoteAddress();
                        std::cout << "\nLocal port: " << client.socket.getLocalPort();
                        std::cout << "probing for server\n / Connection needed to be established to run = false (edit InitConnection fuinction in game.cpp to change) " << sf::IpAddress::LocalHost << "3000\n";


  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: How to reconnect a socket.
« Reply #1 on: October 06, 2022, 07:57:31 pm »
The fix for this was to temporarily change the socket to blocking to re-establish the connection. My game loop then changed it back to false so packets can be received when there is data.


  • SFML Team
  • Hero Member
  • *****
  • Posts: 10936
    • View Profile
    • development blog
    • Email
Re: How to reconnect a socket.
« Reply #2 on: October 06, 2022, 08:22:21 pm »
Not sure what the effect of fluently switching between blocking and non-blocking is, but you can also just loop with sf::sleep() pauses until you get the connection back as an alternative.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
Dev Blog: https://duerrenberger.dev/blog/