Hello
I'm trying to make my Client failsafe - meaning, that should not Crash under any circumstances....so, if something goes wrong, he should just try to reconnect.
Code:
memset(&addr, 0, sizeof(SOCKADDR_IN));
addr.sin_family = AF_INET;
addr.sin_port = htons(12345);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
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;
Sleep(1000);
}else{
// Connection established
while (true)
{
//recv and do stuff
rc = recv(s, buff, 512, 0);
if (rc == SOCKET_ERROR)
break;
}
}
closesocket(s);
Sleep(1000);
}
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?