在我们的网络编程研究中,我们从irDA编程开始,所以我有两个irDA适配器“ Kingsun KS-959 USB红外适配器”和两台运行Windows XP SP2的旧计算机。

我在两台计算机上都正确安装了适配器。

我想在irDA中创建服务器/客户端。这是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;


这是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());
    }
}


在发出连接之前,我一切正常,因此connect仍然卡住,因此未建立连接。

我感谢任何帮助之王

最佳答案

在服务器实现中,将accept()放在while(1)循环中。

您无需在while(1)循环中等待客户端实现中的connect()

服务器

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

10-07 16:26