Skip to content

Instantly share code, notes, and snippets.

@lancetw
Last active December 26, 2015 19:19
Show Gist options
  • Save lancetw/7200234 to your computer and use it in GitHub Desktop.
Save lancetw/7200234 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
using namespace std;
#ifdef _WIN32
#include <windows.h>
void _sleep(unsigned int milliseconds)
{
Sleep(milliseconds);
}
#else
#include <unistd.h>
void _sleep(unsigned int milliseconds)
{
usleep(milliseconds * 1000);
}
#endif
bool sendMsg(const string&, const string&);
bool sendMsgErr(const string&, const string&);
bool sendMsg(const string&, const string&, int, unsigned int);
bool sendMsgRecursion(const string&, const string&, int);
bool sendMsgRecursionErr(const string&, const string&, int);
bool sendMsgRecursion(const string&, const string&, int, unsigned int);
const unsigned int ERROR_TIMES = 3;
unsigned int call_count = 0;
int main(int argc, char *argv[])
{
string server = "127.0.0.1";
string data = "test pass";
cout << "connecting to " << server << " ..." << endl;
bool result = sendMsgRecursion(server, data, 3, 1000);
if (result) {
cout << "result: success" << endl;
} else {
cout << "result: failure" << endl;
}
return 0;
}
bool sendMsg(const string& server, const string& data, int retry_times, unsigned int retry_interval_milliseconds)
{
bool flag = false;
if (retry_times <= 0) return flag;
for (; retry_times > 0; retry_times--) {
try {
flag = sendMsgErr(server, data);
if (flag) break;
} catch (...) {
cout << "retry: " << retry_times << endl;
_sleep(retry_interval_milliseconds);
}
}
return flag;
}
bool sendMsg(const string& server, const string& data)
{
bool flag = false;
cout << server << endl;
cout << data << endl;
flag = true;
return flag;
}
bool sendMsgErr(const string& server, const string& data)
{
call_count++;
if (call_count <= ERROR_TIMES) {
throw "err_code";
} else {
return sendMsg(server, data);
}
}
bool sendMsgRecursion(const string& server, const string& data, int retry_times, unsigned int retry_interval_milliseconds)
{
if (retry_times <= 0) return false;
try {
return sendMsgRecursionErr(server, data, retry_times--);
} catch (...) {
cout << "retry: " << retry_times+1 << endl;
_sleep(retry_interval_milliseconds);
return sendMsgRecursion(server, data, retry_times--, retry_interval_milliseconds);
}
}
bool sendMsgRecursion(const string& server, const string& data, int retry_times)
{
bool flag = false;
cout << server << endl;
cout << data << endl;
flag = true;
return flag;
}
bool sendMsgRecursionErr(const string& server, const string& data, int retry_times)
{
call_count++;
if (call_count <= ERROR_TIMES) {
throw "err_code";
} else {
return sendMsgRecursion(server, data, retry_times);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment