用c++实现TCP/Ip网络通信

TCP/Ip network communication in c++

本文关键字:Ip 网络通信 TCP c++ 实现      更新时间:2023-10-16

我正在尝试编写一个线程函数,该函数通过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);

现在它工作得非常好,不过感谢您提供的故障排除技巧!