March 15th Monday 2010

作者为项目编写了一个基于UDP的通用通信模块,该模块分为发送端和接收端两部分。在调试过程中遇到问题,发送消息后总是收到超时错误,问题疑似出现在接收消息的函数中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  I wrote a common communication module for our project.  It is based on the UDP.  It is alike C/S.  I divided it into two parts, sender and receiver.

 

  I just made a simple wrap for UDP socket functions.  It may not be enough.  I don't know what is needed.  Oh.  Okay.  Today I begin to debug it.  Tomorrow it must can be tested by us.

 

unsigned int XXXCls::Send(const void *buf, const unsigned long buf_len)
{
...
 struct sockaddr_in ackAddr;                 // 回复的地址
 int ackAddrLen = 0;           // 回复的地址的长度
 int rc = 0;

 

 // 生成待发送的消息
 ...

 

 // 发送
 while (count > 0) {

  SendMsg(m_sock, (char *)&msg, msg_size, (SOCKADDR *)&m_destAddr, sizeof(m_destAddr));

  // 接收回复
  rc = RecvMsg(m_sock, (char *)&ack, sizeof(ack), (SOCKADDR *)&ackAddr, &ackAddrLen);
  if (jyCOM_OK == rc) {
   
   // 解析回复

  ...

  count--;
 }

 if (0 == count)
  ret = jyCOM_TIMEOUT;

 return ret;
}

 

 The above function always return a time out error.   The red line is the root of the bug.  Look at the function RecvMsg().

 

unsigned int RecvMsg(const SOCKET sock, char* buf, unsigned long buf_size, SOCKADDR * srcAddr, int * addrLen)
{
 int ret = 0;
 fd_set read_set;
 struct timeval timeout;
 int rc = 0;
 int recv_num = 0;

 // 初始化
 FD_ZERO(&read_set);
 FD_SET(sock, &read_set);

 memset(&timeout, 0, sizeof(struct timeval));
 timeout.tv_sec = COM_TIMEOUT_SEC;
 timeout.tv_usec = 0;

 rc = select(1, &read_set, NULL, NULL, &timeout);
 if (rc == SOCKET_ERROR)
  ret = COM_SEND_ERROR;
 else if (rc == 0)
  ret = COM_TIMEOUT;
 else {
  recv_num = recvfrom(sock, buf, buf_size, 0, srcAddr, addrLen);
 
  // 接收出错
  if (recv_num == SOCKET_ERROR)
   ret = COM_RECV_ERROR;
 }

 return ret;
}

 

The last parameter of recvfrom function is an in out parameter.  So, when ackAddrLen is 0, window considers my application passed an invalid pointer value, or it the length of the buffer is too small.  For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).   In fact, I just made the mistake.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值