用c++实现TCP/Ip网络通信
TCP/Ip network communication in c++
我正在尝试编写一个线程函数,该函数通过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;
}
我认为我对这些函数做了错误的处理,问题不在接收这些数据的线路的另一边。有人能在这段代码中看到任何可能导致失败的明显错误吗?我一直收到我自己的定制消息"Monitor: FAILED TO OPEN SOCKET FOR DATA"
编辑:使用telnet,一切都很好,100%的时间
您可以使用netstat检查服务器是否正在侦听端口以及连接是否正在建立。Snoop是Armour中另一个很好的应用程序,可以发现问题所在。另一种可能性是使用telnet
来查看客户端是否可以连接到该IP地址和端口。至于代码,我稍后会查看它,看看是否出了问题。
socket
是一个全局变量。它可以在两个线程之间同时重复使用,也可以在一个线程内按顺序重复使用。事实上,while(~closeProgram)
循环表示您打算按顺序使用它。
CActiveSocket::Open
的一些文档写道:"基于连接的协议套接字(CSocket::SocketTypeTcp)只能成功调用Open()一次…"
当您对同一对象调用.Open()
两次时,可能您的程序失败了。
我最终发现了代码的问题。由于连接不稳定,70%的时间都在工作,这似乎是一个超时问题。我删除了的两个超时设置
socket.SetConnectTimeout(0, 20);
socket.SetSendTimeout(0, 20);
现在它工作得非常好,不过感谢您提供的故障排除技巧!
相关文章:
- 是否有一种标准化的方法通过TCP/IP网络发送JPG图像
- 检查IP是否在其他IP网络范围内,并查找下一个可用IP
- UDP客户端/服务器程序在不同的IP和端口上通信超过2个插座
- 在网络C 上获取计算机的IP地址
- 网络传输时间从TCP/IP堆栈
- UDP通信中的端口和IP地址用法
- 如何在我当前连接的网络中获取本地 IP 地址?
- 在c++(WLANAPI)中获取Windows wifi托管网络设备的ip地址
- 如何在没有网络表条目上下文时删除 IP 地址
- 使用Boost.ASIO与服务器进行简单的网络tcp通信
- 如何获取本地网络上所有设备的名称和 ip
- 定义网络通信的结构
- 通过网络在应用程序之间进行通信
- Qt,tcp/ip通信校验和
- 用c++实现TCP/Ip网络通信
- Qt TCP/IP通信只能在本地工作,但在网络中会丢失
- Qt和Node JS通过WebSockets进行网络通信
- PLC和网络通信:概念基础
- C/ c++ Posix tcp/ip网络客户端,只连接到本地主机
- IP网络中的动态松源路由