VS2010 MFC UDP数据接收

1、  线程中创建连接,断开时自动会重连

SOCKET g_socket;

DWORD WINAPIThreadConnectDevice(LPVOID wParam)

{

         uint16_t port = 42000; // Default is UDP port 42000

         while(1)

         {

                   intret = startUDPConnection(port, &g_socket);

                   if(ret == RESULT_OK)

                   {                                  

Receiver(&g_socket);//接收处理

                                     stopUDPConnection(&g_socket);

                   }

                   else

                   {

                                     Sleep(10);

                   }

         }      

}

         return 0;

}

(2)startUDPConnection

int startUDPConnection(uint16_t port, SOCKET*pSocket)

{

    WSADATA wsa;

    SOCKADDR_IN addr;

    int ret;

    int rc;

    // Start Winsock

    ret = WSAStartup(MAKEWORD(2,0),&wsa);

    if (ret !=0)

    {

        TRACE("Can'tstart Windows Socks API\n");

        returnRESULT_ERROR;

    }

    // create socket

    *pSocket = socket(AF_INET,SOCK_DGRAM,0);

    if(*pSocket== INVALID_SOCKET)

    {

        TRACE("Coudln'tcreate the UDP socket\n");

        returnRESULT_ERROR;

    }

    // bind socket toport

    addr.sin_family=AF_INET;

    addr.sin_port=htons(port);

    addr.sin_addr.s_addr=ADDR_ANY;

    rc=bind(*pSocket,(SOCKADDR*)&addr,sizeof(SOCKADDR_IN));

    if(rc==SOCKET_ERROR)

    {

        TRACE("Binddidn't work, error code: %d\n",WSAGetLastError());

        returnRESULT_ERROR;

    }

    returnRESULT_OK;

}

(3)数据接收

 

int Receiver(SOCKET* pSocket)

{

    // holds thesender information of the received packet

    structsockaddr remoteAddr;

    int32_t remoteAddrLen;

   

    // buffer for asingle UDP packet

   int8_t udpPacketBuf[UDP_PACKET_BUF_LEN];

 

    remoteAddrLen=sizeof(struct sockaddr);

        

    // run for alleternity as long as no error occurs

    while (1)

    {                 

        // receivethe data. rc contains the number of received bytes and also the error code

        // IMPORTANT:This is a blocking call. If it doesn't receive anything it will wait forever

        int32_t rc=recvfrom(*pSocket,(char*)udpPacketBuf,UDP_PACKET_BUF_LEN,0,&remoteAddr,&remoteAddrLen);

        if(rc==SOCKET_ERROR)

        {

            TRACE("Errorin recvfrom, error code: %d\n",WSAGetLastError());

            returnRESULT_ERROR;

        }

        else

        {

//对接收数据的处理          

        }         

    }        

    returnRESULT_OK;

}

(4)关闭连接

void stopUDPConnection(SOCKET* pSocket)

{

    closesocket(*pSocket);

    WSACleanup();

}

你可能感兴趣的:(MFC-VS2010)