Chitika

Wednesday, January 25, 2012

c++ Win UDP Communication

Init:

    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR) {
        wprintf(L"WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

SOCKET sockRecv,
        sockSend;


Send:

        sockSend = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        addr.sin_family = AF_INET;
        addr.sin_port = htons(srcPort);
        addr.sin_addr.s_addr = INADDR_ANY;

        bind(sockSend, (sockaddr *) &addr, sizeof(addr));

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(dstPort);
    addr.sin_addr.s_addr = inet_addr(this->ipAddress.c_str());

    lastMsgLen = SerialLength;
    memcpy(lastMsg, Buffer, lastMsgLen);
    int ret = sendto(sockSend, (char *)Buffer, SerialLength, 0, (SOCKADDR *) &addr, sizeof(addr));


Receive:



        sockRecv = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(this->port+1);
        addr.sin_addr.s_addr = INADDR_ANY;

        bind(sockRecv, (sockaddr *) &addr, sizeof(addr));

       struct sockaddr_in raddr;
       int fromLen = sizeof(raddr);

       fd_set rd;
        FD_ZERO(&rd);
        FD_SET(sockRecv, &rd);
        timeval tv;
        tv.tv_sec = 2;
        tv.tv_usec = 0;

        if(select(0, &rd, NULL, NULL, &tv) > 0) {

            if(FD_ISSET(sockRecv, &rd)) {
                int recv = recvfrom(sockRecv, (char *) &pktRecv, sizeof(pktRecv), 0, (sockaddr *)&raddr, &fromLen);
                readStatus = 1;
                break;
            } else {
                ResentLastMsg();
                readStatus = 0;
            }

        } else {
            ResentLastMsg();
            readStatus = 0;
        }

Shutdown:

    WSACleanup();

No comments:

Post a Comment