现在的位置: 首页 > 综合 > 正文

March 15th Monday 2010

2013年11月17日 ⁄ 综合 ⁄ 共 1689字 ⁄ 字号 评论关闭

  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.

抱歉!评论已关闭.