udp winsock编程

时间:2010-10-05 04:53:15

标签: udp winsock

我是套接字编程的初学者。我想从端口连续接收udp数据包。为此,我创建了套接字并使用我已完成程序的bind和recv调用。在缓冲区中我存储udp数据包。如何按包接收数据包。如何为特定时间间隔设置条件?提前致谢。

static int recvData = 1;
sockID = socket(AF_INET, SOCK_DGRAM, 0);
 if(sockID < 0)
 {
  printf("Socket creation error\n");
        WSACleanup();
 }
 else
 {
  printf("Socket Created\n");
 }

 fepAddr.sin_family = AF_INET;
 fepAddr.sin_port = htons(inputData.portNo);
 fepAddr.sin_addr.s_addr = inet_addr(inputData.destIPAddr);

 if (bind(sockID, (struct sockaddr *)&fepAddr, sizeof(fepAddr)) == SOCKET_ERROR)
 {
  printf("bind() failed: %ld.\n", WSAGetLastError());
  closesocket(sockID);
  return 0;
 }

 else
 {
  printf("bind() is OK!\n");
 }

 memset(udpBuf,sizeof(udpBuf),0);
 while (recvData)
 {
  printf("receiving data\n");
  recvResult =  recvfrom( sockID, udpBuf, sizeof(udpBuf), 0,(struct sockaddr *)&fepAddr, &sock_len); 


  fprintf(udp, "%s", udpBuf);
  //fwrite(udpBuf, sizeof(udpBuf), 1, udp);
  recvData-- ;
 }
exit:
    if(udp) 
    {
         fclose(udp);
         udp = 0; 
    }

 //shutdown socket
 closesocket(sockID); 
 fclose(udp);

1 个答案:

答案 0 :(得分:1)

recvfrom()逐包接收UDP数据。如果给定数据包太大,recvfrom()将返回错误。至于计时,你可以使用select()来知道套接字何时可读。

尝试这样的事情:

sockID = socket(AF_INET, SOCK_DGRAM, 0); 
if (sockID == INVALID_SOCKET) 
{ 
  printf("Socket creation error\n"); 
  goto exit;
} 

printf("Socket Created\n"); 

memset(&fepAddr, 0, sizeof(fepAddr));
fepAddr.sin_family = AF_INET; 
fepAddr.sin_port = htons(inputData.portNo); 
fepAddr.sin_addr.s_addr = inet_addr(inputData.destIPAddr); 

if (bind(sockID, (struct sockaddr *)&fepAddr, sizeof(fepAddr)) == SOCKET_ERROR) 
{ 
  printf("bind() failed: %ld.\n", WSAGetLastError()); 
  goto exit;
} 

printf("bind() is OK!\n"); 

memset(udpBuf, 0, sizeof(udpBuf)); 

printf("receiving data\n"); 
while (...) 
{
  printf("."); 

  recvResult = recvfrom(sockID, udpBuf, sizeof(udpBuf), 0, (struct sockaddr *)&fepAddr, &addr_len);  
  if (recvResult == SOCKET_ERROR)
  {
    if (WSAGetLastError() != WSAEWOULDBLOCK)
    {
      printf("\nrecvfrom() failed: %ld.\n", WSAGetLastError()); 
      goto exit;
    }

    fd_set fd;
    FD_ZERO(&fd);
    FD_SET(sockID, &fd);

    timeval t;
    t.tv_sec = ...; // seconds
    t.tv_usec = ...; // microseconds

    selectResult = select(0, &fd, NULL, NULL, &t);
    if (selectResult == SOCKET_ERROR)
    {
      printf("\nselect() failed: %ld.\n", WSAGetLastError()); 
      goto exit;
    }

    if (selectResult == 0)
    {
      printf("\nsocket timed out.\n");
      goto exit;
    }

    continue;
  }

  if (recvResult > 0)
    fwrite(udpBuf, recvResult, 1, udp); 
} 

exit: 
  if (udp != 0)
  { 
    fclose(udp); 
    udp = 0;  
  } 

  if (sockID != INVALID_SOCKET) 
  {
    closesocket(sockID);  
    sockID = INVALID_SOCKET;
  }