Thread: [C++] Failsafe Winsock connection

  1. #1
    Registered User
    Join Date
    Oct 2013

    [C++] Failsafe Winsock connection

    I'm trying to make my Client failsafe - meaning, that should not Crash under any, if something goes wrong, he should just try to reconnect.

    memset(&addr, 0, sizeof(SOCKADDR_IN));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(12345);
    addr.sin_addr.s_addr = inet_addr("");
    rc = startWinsock();
    if (rc != 0) {
          cout << "Error: startWinsock, Error code: " << rc << endl;
          return 1;
    while (rc == 0 || rc == SOCKET_ERROR || rc == 4){
          s = socket(AF_INET, SOCK_STREAM, 0);
          if (s == INVALID_SOCKET){
                cout << "Error: Couldn't create socket, code: " << WSAGetLastError() << endl;
                return 1;
          rc = connect(s, (SOCKADDR*)&addr, sizeof(SOCKADDR)); 
          if (rc == SOCKET_ERROR)
                 cout << "Connection failed with code " << WSAGetLastError() << endl;
                  // Connection established
                  while (true)
                       //recv and do stuff
                       rc = recv(s, buff, 512, 0);
                       if (rc == SOCKET_ERROR)
    The connection is working and if I close the server, it loses the connection and tries to reconnect, which is good. However, I'm not sure if the way I did it was right. Any improvements?

    Then the main question: What else can go wrong? How do I make sure, that if anything happens in the recv Loop, it will just quit and reconnect and start from beginning?

  2. #2
    train spotter
    Join Date
    Aug 2001
    near a computer
    Add some exception handling and process known errors?

    Is this a state machine? (ie will know if it fails to return to the 'connection' state, from the 'reading' state)?
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. winsock - how to reject connection?
    By symbiote in forum Networking/Device Communication
    Replies: 4
    Last Post: 03-13-2009, 10:28 AM
  2. Winsock connection problem
    By Nephiroth in forum C++ Programming
    Replies: 2
    Last Post: 02-07-2006, 07:54 AM
  3. weird winsock output and winsock 2 not working
    By whackaxe in forum Networking/Device Communication
    Replies: 4
    Last Post: 07-09-2004, 11:10 AM
  4. Varifying Socket Connection :: Winsock
    By kuphryn in forum Windows Programming
    Replies: 3
    Last Post: 05-11-2002, 03:26 PM
  5. Listening for connection in Winsock?
    By SyntaxBubble in forum Windows Programming
    Replies: 11
    Last Post: 11-29-2001, 12:28 AM