Search code examples
c++network-programminginfrared

how to establish connection through irDA sockets?


in our study of network programming we began with irDA programming so I have two irDA adapters "Kingsun KS-959 USB Infrared Adapter" and two old computers running windows xp sp2.

I installed correctly the adapters on both machines.

I wanted to create Server/Client in irDA. here is a sample of irServer irClient:

// irServer:

#define BACKLOG 2
WORD    wVersion = MAKEWORD(2, 2);
WSADATA wSaData;

if(WSAStartup(wVersion, &wSaData))
    return -1;

int irSockServ = socket(AF_IRDA, SOCK_STREAM, 0);

if(SOCKET_ERROR == irSockServ)
    DieWithError(WSAGetLastError());

SOCKADDR_IRDA sa_irda_serv = {AF_IRDA, 0, 0, 0, 0, 
                            "irDA:irCOMM"};
if(SOCKET_ERROR == bind(irSockServ, (SOCKADDR*)&sa_irda_serv, sizeof(sa_irda_serv)))
    DieWithError(WSAGetLastError());
if(SOCKET_ERROR == listen(irSockServ, BACKLOG))
    DieWithError(WSAGetLastError());

SOCKADDR_IRDA sa_irda_clnt;
int sa_irda_clnt_len = sizeof(sa_irda_clnt);
int irSockClnt = accept(irSockServ, (SOCKADDR*)&sa_irda_clnt, &sa_irda_clnt_len);

if(SOCKET_ERROR == irSockClnt)
    DieWithError(WSAGetLastError());
else
    cout << "Client! Connected" << std::endl;

and here is a sample of irClient:

WORD    wVersion = MAKEWORD(2, 2);
WSADATA wSaData;

if(WSAStartup(wVersion, &wSaData))
    return -1;

int irSockClnt = socket(AF_IRDA, SOCK_STREAM, 0);

if(SOCKET_ERROR == irSockClnt)
    DieWithError(WSAGetLastError());

DEVICELIST DevLst;
int DevLstLen = sizeof(DEVICELIST);

while(1)
{
    Sleep(1000);
    DevLst.numDevice = 0;

    // enumerating in range irDA devices
    if(SOCKET_ERROR == getsockopt(irSockClnt, SOL_IRLMP, 
        IRLMP_ENUMDEVICES, (char*)&DevLst, &DevLstLen))
        DieWithError(WSAGetLastError());
    if(DevLst.numDevice)
    {
        cout << "Device Name: " << DevLst.Device[0].irdaDeviceName << endl;

        SOCKADDR_IRDA sa_irda_serv;
        sa_irda_serv.irdaAddressFamily = AF_IRDA;
        strcpy(sa_irda_serv.irdaServiceName, "irDA:irCOMM");
        memcpy(&sa_irda_serv.irdaDeviceID[0], &DevLst.Device[0].irdaDeviceID[0], 4);

        // the problem is here it still stuck and won't connect!??
        if(SOCKET_ERROR == connect(irSockClnt, (SOCKADDR*)&sa_irda_serv, sizeof(sa_irda_serv)))
            DieWithError(WSAGetLastError());
    }
}

I get everything working until issuing a connection so connect still stuck and therefore no connection is established.

I appreciate any king of help


Solution

  • In the server implementation, placeaccept() in a while(1) loop.

    You don't need to wait in the while(1) loop for the connect() in the client implementation.

    Server

    while(1) {
    ...
     accept(...);
     Sleep(Number_of_miliseconds);//You are using win32 imp, for POSIX sleep() this will be in seconds
    ...
    }