我正在尝试编写一个线程函数,通过本地网络上的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