gpt4 book ai didi

c++ - C++中的TCP/IP网络通信

转载 作者:行者123 更新时间:2023-11-28 08:00:59 24 4
gpt4 key购买 nike

我正在尝试编写一个线程函数,通过本地网络上的 Tcp/ip 将系统信息发送到另一台计算机。我一直在使用套接字来实现这一点,到目前为止效果还不错。但我现在处于通常可以正常工作的地步,但大约 30% 的时间我收到错误消息,告诉我无法打开套接字。我将 activeSocket 库用于套接字。

#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% 的时间

最佳答案

您可以使用 netstat检查服务器是否正在监听端口并且正在建立连接。 Snoop是您的 Armor 中用于找出问题所在的另一个很好的应用程序。另一种可能性是使用 telnet 查看客户端是否可以连接到该 IP 地址和端口。至于代码,我稍后会看一下,看看是否出了什么问题。

关于c++ - C++中的TCP/IP网络通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11472019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com