我正在嘗試編寫一個線程函數,通過本地網絡上的TCP/IP發送系統信息到另一臺計算機。我一直在使用套接字來實現這一點,到目前爲止,這已經非常成功。但我現在處於這種情況通常可以正常工作的時間點,但大約有30%的時間我收到錯誤消息,告訴我無法打開套接字。我使用activeSocket庫作爲套接字。在c + +中的TCP/IP網絡通信
#include "tbb/tick_count.h"
#include "ActiveSocket.h"
using namespace std;
CActiveSocket socket;
extern int hardwareStatus;
int establishTCP() {
char time[11];
int communicationFailed = 0;
memset(&time, 0, 11);
socket.Initialize();
socket.SetConnectTimeout(0, 20);
socket.SetSendTimeout(0, 20);
return communicationFailed;
}
int monitor() {
cout << "Monitor: init continious monitoring" << endl;
int communicationFailed;
tbb::tick_count monitorCounter = tbb::tick_count::now();
while (!closeProgram) {
tbb::tick_count currentTick = tbb::tick_count::now();
tbb::tick_count::interval_t interval;
interval = currentTick - monitorCounter;
if (interval.seconds() > 2) {
monitorCounter = tbb::tick_count::now();
communicationFailed = 1;
char buffer[256];
sprintf(buffer, "%d;", hardwareStatus);
establishTCP();
char *charip = new char[monitoringIP.size() + 1];
charip[monitoringIP.size()] = 0;
memcpy(charip, monitoringIP.c_str(), monitoringIP.size());
const uint8* realip = (const uint8 *) charip;
int monitorCount = 0;
cout << "Monitor: " << buffer << endl;
while (communicationFailed == 1 && monitorCount < 2) {
monitorCount++;
if (socket.Open(realip, 2417)) {
if (socket.Send((const uint8 *) buffer, strlen(buffer))) {
cout << "Monitor: Succeeded sending data" << endl;
communicationFailed = 0;
socket.Close();
} else {
socket.Close();
communicationFailed = 1;
cout << "Monitor: FAILED TO SEND DATA" << endl;
}
} else {
socket.Close();
communicationFailed = 1;
cout << "Monitor: FAILED TO OPEN SOCKET FOR DATA" << endl;
}
}
if (monitorCount == 2) cout << "Monitor: UNABLE TO SEND DATA" << endl;
}
}
return communicationFailed;
}
我認爲我在做這些功能有問題,並且問題不在接收此數據的行的另一端。任何人都可以在這段代碼中看到任何可能導致失敗的明顯錯誤嗎?我一直讓我自己COUT消息"Monitor: FAILED TO OPEN SOCKET FOR DATA"
編輯:使用Telnet一切正常,100%的時間
名稱爲「socket」的變量的類型是什麼? – 2012-07-13 15:07:27
哎呀,忘了更改名稱,這是一個CActiveSocket – 2012-07-13 15:12:06