⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 btsquirt.cpp

📁 《Windows CE 6.0开发者参考》(《Programming Windows Embedded CE 6.0 Developer Reference》)第四版书中的源代码
💻 CPP
📖 第 1 页 / 共 2 页
字号:
                          WORD wNotifyCode) {

    SendMessage (hWnd, WM_CLOSE, 0, 0);
    return 0;
}
//----------------------------------------------------------------------
// DoMainCommandSend - Process Program Send File command.
//
LPARAM DoMainCommandSend (HWND hWnd, WORD idItem, HWND hwndCtl,
                          WORD wNotifyCode) {
    const LPTSTR pszOpenFilter = TEXT ("All Documents (*.*)\0*.*\0\0");
    OPENFILENAME of;
    HANDLE hTh;

    PSENDTHSTRUCT psfs = (PSENDTHSTRUCT) malloc (sizeof (SENDTHSTRUCT));
    if (psfs == 0) {
        Add2List (hWnd, TEXT("Out of memory."));
        return 0;
    }

    memset (&of, 0, sizeof (of));
    of.lStructSize = sizeof (of);
    of.lpstrTitle = TEXT("Select file to send");
    of.lpstrFile = psfs->szName;
    of.nMaxFile = dim (psfs->szName);
    of.lpstrFilter = pszOpenFilter;
    if (!GetOpenFileName (&of))
        return 0;

    // Open the file.
    psfs->hFile = CreateFile (psfs->szName, GENERIC_READ, 
                              FILE_SHARE_READ, NULL, OPEN_EXISTING,
                              0, NULL);
    if (psfs->hFile == INVALID_HANDLE_VALUE) {
        Add2List (hWnd, TEXT("File open failed. rc %d"), 
                  GetLastError());
        return -1;
    }
    psfs->nDevice = (int)SendDlgItemMessage (hWnd, IDD_DEVICES, 
                                             CB_GETCURSEL, 0, 0);
    // Send the file on another thread.
    hTh = CreateThread (NULL, 0, SendFileThread, (PVOID)psfs, 0, NULL);
    CloseHandle (hTh);
    return 0;
}
//----------------------------------------------------------------------
// DoMainCommandScan - Process Device Scan command.
//
LPARAM DoMainCommandScan (HWND hWnd, WORD idItem, HWND hwndCtl,
                          WORD wNotifyCode) {
    HANDLE hTh;
    SetWindowText (hWnd, TEXT("Scanning..."));
    EnableWindow (GetDlgItem (hWnd, IDD_SENDFILE), FALSE);
    EnableWindow (GetDlgItem (hWnd, IDD_SCAN), FALSE);
    SendDlgItemMessage (hWnd, IDD_DEVICES, CB_RESETCONTENT, 0, 0);
    hTh = CreateThread (NULL, 0, SearchThread, (PVOID)hWnd, 0, NULL);
    CloseHandle (hTh);
    return 0;
}
//----------------------------------------------------------------------
// Add2List - Add string to the report list box.
//
void Add2List (HWND hWnd, LPTSTR lpszFormat, ...) {
    int nBuf, nLen;
    TCHAR szBuffer[512];
    va_list args;
    if (hWnd == 0)
        hWnd = hMain;

    EnterCriticalSection (&csPrintf);
    va_start(args, lpszFormat);
    nBuf = StringCchVPrintf (szBuffer, dim(szBuffer), lpszFormat, args);
    va_end(args);

    nLen = (lstrlen (szBuffer)+1) * sizeof (TCHAR);
    WriteMsgQueue (hQWrite, (LPBYTE)szBuffer, nLen, 0, 0);
    PostMessage (hWnd, MYMSG_PRINTF, 0, 0);
    LeaveCriticalSection (&csPrintf);
}
//----------------------------------------------------------------------
// MySetWindowText - Set Window title to passed printf style string.
//
void MySetWindowText (HWND hWnd, LPTSTR lpszFormat, ...) {
    int nBuf, nLen;
    TCHAR szBuffer[512];
    va_list args;

    EnterCriticalSection (&csPrintf);
    va_start(args, lpszFormat);
    nBuf = StringCchVPrintf (szBuffer, dim (szBuffer), lpszFormat, args);
    va_end(args);

    nLen = (lstrlen (szBuffer)+1) * sizeof (TCHAR);
    WriteMsgQueue (hQWrite, (LPBYTE)szBuffer, nLen, 0,MSGQUEUE_MSGALERT);
    PostMessage (hWnd, MYMSG_PRINTF, 0, 0);
    LeaveCriticalSection (&csPrintf);
}
//======================================================================
// SearchThread - Monitors for other devices.
//
DWORD WINAPI SearchThread (PVOID pArg) {
    HWND hWnd = (HWND)pArg;
    int i, rc, Channel = 0;

    Add2List (hWnd, TEXT("Search thread entered"));

    // Init COM for the thread.
    CoInitializeEx(NULL,COINIT_MULTITHREADED);

    // Find the Bluetooth devices
    nDevs = MAX_DEVICES;
    rc = FindDevices (btd, &nDevs);

    // List them.
    for (i = 0; i < nDevs; i++) {
        PostMessage (hWnd, MYMSG_NEWDEV, i, (LPARAM)btd[i].szName);
        Add2List (hWnd, TEXT("%d. dev:>%s<  "), i, btd[i].szName);
    }
    PostMessage (hWnd, MYMSG_ENABLESEND, 0, 1);
    CoUninitialize();
    Add2List (hWnd, TEXT("Search thread exit"));
    return 0;
}
//======================================================================
// ServerThread - Monitors for connections, connnects and notifies
// user when a connection occurs.
//
DWORD WINAPI ServerThread (PVOID pArg) {
    HWND hWnd = (HWND)pArg;
    INT rc, len, nSize;
    SOCKADDR_BTH btaddr, t_btaddr;
    SOCKET r_sock;
    ULONG RecordHandle;
    HRESULT hr;

    Add2List (hWnd, TEXT("Server thread entered"));
    CoInitializeEx(NULL,COINIT_MULTITHREADED);

    // Print out our name
    char sz[256];
    gethostname (sz, 256);
    Add2List (hWnd, TEXT("This device name: %S"), sz);
    
    // Open a bluetooth socket
    s_sock = socket (AF_BT, SOCK_STREAM, BTHPROTO_RFCOMM);
    if (s_sock == INVALID_SOCKET) {
        Add2List (hWnd, TEXT("socket failed. rc %d"),WSAGetLastError());
        return 0;
    }
    // Fill in address stuff
    memset (&btaddr, 0, sizeof (btaddr));
    btaddr.addressFamily = AF_BT;
    btaddr.port = 0;   // Let driver assign a channel

    // Bind to socket
    rc = bind (s_sock, (struct sockaddr *)&btaddr, sizeof (btaddr));
    if (rc) {
        Add2List (hWnd, TEXT("bind failed"));
        closesocket (s_sock);
        return 0;
    }
    // Get information on the port assigned
    len = sizeof (btaddr);
    rc = getsockname (s_sock, (SOCKADDR *)&btaddr, &len);
    if (rc) {
        Add2List (hWnd, TEXT("getsockname failed"));
        closesocket (s_sock);
        return 0;
    }
    Add2List (hWnd, TEXT("Addr %04x.%08x, port %d"), 
           GET_NAP(btaddr.btAddr), GET_SAP(btaddr.btAddr), btaddr.port);

    // Register our service
    rc = RegisterBtService (&guidBtSquirt, (unsigned char) btaddr.port, 
                            &RecordHandle);
    if (rc) {
        Add2List (hWnd, TEXT("RegisterService fail %d %d"), rc, 
                  GetLastError());
        closesocket (s_sock);
        return 0;
    }
    
    // Set socket into listen mode
    rc = listen (s_sock, SOMAXCONN);
    if (rc == SOCKET_ERROR) {
        Add2List (hWnd, TEXT(" listen failed %d"), GetLastError());
        closesocket (s_sock);
        return 0;
    }
    // Wait for remote requests
    while (fContinue) {
        Add2List (hWnd, TEXT("waiting..."));
        nSize = sizeof (t_btaddr);
        // Block on accept
        r_sock = accept (s_sock, (struct sockaddr *)&t_btaddr, &nSize);
        if (r_sock == INVALID_SOCKET) {
            Add2List (hWnd, TEXT(" accept failed %d"), GetLastError());
            break;
        }
        Add2List (hWnd, TEXT("sock accept..."));
        HANDLE h = CreateThread (NULL, 0, ReceiveThread, (PVOID)r_sock, 0, NULL);
        CloseHandle (h);
    }
    closesocket (s_sock);

    // Deregister the service
    hr = UnregisterBtService (hWnd, RecordHandle);
    CoUninitialize();
    Add2List (hWnd, TEXT("Server thread exit"));
    return 0;
}
//======================================================================
// ReceiveThread - Receives the file requested by the remote device
//
DWORD WINAPI ReceiveThread (PVOID pArg) {
    SOCKET t_sock = (SOCKET)pArg;
    HWND hWnd = hMain; // I抦 cheating here.
    int nCnt, nFileSize, rc;
    TCHAR szFileName[MAX_PATH];
    PBYTE pBuff;
    int i, nSize, nTotal;
    DWORD dwBytes;
    HANDLE hFile;
    Add2List (hWnd, TEXT("receive thread entered"));
    SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_ABOVE_NORMAL);

    // Read the number of bytes in the filename.
    rc = recv (t_sock, (LPSTR)&nCnt, sizeof (nCnt), 0);
    if ((rc == SOCKET_ERROR) || (nCnt > MAX_PATH)) {
        Add2List (hWnd, TEXT("failed receiving name size"));
        closesocket (t_sock);
        return 0;
    }
    // Read the filename. Place the file in the root of the file system
    StringCchCopy (szFileName, dim (szFileName), L"\\"); 
    i = (int) wcslen (szFileName);             
    rc = recv (t_sock, (LPSTR)&szFileName[i], nCnt, 0);
    if (rc == SOCKET_ERROR) {
        Add2List (hWnd, TEXT("failed receiving name"));
        closesocket (t_sock);
        return 0;
    }
    Add2List (hWnd, TEXT("File: %s"), szFileName);

    pBuff = (PBYTE)LocalAlloc (LPTR, BLKSIZE); //Create buff for file.
    //
    // Receive file size.
    //
    rc = recv (t_sock, (LPSTR)&nFileSize, sizeof (nFileSize), 0);
    Add2List (hWnd, TEXT("received file size of %d bytes"), nFileSize);

    if ((rc != SOCKET_ERROR) && (nFileSize > 0)) {
        // Create the file. Overwrite if user says so.
        rc = 0;
        hFile = CreateFile (szFileName, GENERIC_WRITE, 0, NULL,
                            CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        if (hFile == INVALID_HANDLE_VALUE) {
            Add2List (hWnd, TEXT("File Open failed. rc %d"), 
                      GetLastError());
            rc = BAD_FILEWRITE;
        }
        // Send ack code.
        Add2List (hWnd, TEXT("Sending ack. %d"), rc); 
        send (t_sock, (LPSTR)&rc, sizeof (rc), 0);
        //
        // Receive file.
        //
        nTotal = nFileSize;
        while ((!rc) && (nFileSize > 0)) {

            MySetWindowText (hWnd, TEXT ("%02d%% received"), 
                      (nTotal-nFileSize)*100/nTotal);
            nCnt = min (BLKSIZE, nFileSize);
            for (nSize = 0; nSize < nCnt;) {
                i = recv (t_sock, (LPSTR)pBuff+nSize, nCnt-nSize, 0);
                if (i == SOCKET_ERROR) {
                    Add2List (hWnd, TEXT("recv socket err %d"), 
                              GetLastError()); 
                    rc = BAD_SOCKETRECV;
                    break;
                } 
                nSize += i;
            }
            Add2List (hWnd, TEXT("recv抎 %d bytes."), nSize); 
            if (i) {
                if (!WriteFile (hFile, pBuff, nSize, &dwBytes, 0))
                    rc = BAD_FILEWRITE;
                nFileSize -= dwBytes;
            } else
                Sleep(50);
            // Send ack of packet.
            send (t_sock, (LPSTR)&rc, sizeof (rc), 0);
        }
    } else if (rc == BAD_FILEOPEN)
        Add2List (hWnd, TEXT("File not found.")); 
    Add2List (hWnd, TEXT("receive finished"));
    LocalFree (pBuff);  
    CloseHandle (hFile);
    SetWindowText (hWnd, szTitleText);
    Add2List (hWnd, TEXT("receive thread exit"));
    return 0;
}

//----------------------------------------------------------------------
// SendThread - Sends a file to the remote device
// 
DWORD WINAPI SendFileThread (PVOID pArg) {
    PSENDTHSTRUCT psfs = (PSENDTHSTRUCT) pArg;
    HWND hWnd = hMain;
    SOCKET t_sock;
    int i, rc, nCnt, nBytes, nTotal = 0;
    SOCKADDR_BTH btaddr;
    BOOL fSuccess = FALSE;
    char *pBuff;

    // Open a bluetooth socket
    t_sock = socket (AF_BT, SOCK_STREAM, BTHPROTO_RFCOMM);
    if (t_sock == INVALID_SOCKET) {
        Add2List (hWnd, TEXT("socket failed. rc %d"),WSAGetLastError());
        return 0;
    }
    Add2List (hWnd, TEXT("Trying device %s"), btd[psfs->nDevice].szName);

    // Fill in address stuff
    memset (&btaddr, 0, sizeof (btaddr));
    btaddr.btAddr = btd[psfs->nDevice].btaddr;
    btaddr.addressFamily = AF_BT;
    btaddr.port = 0;                  // Let driver find the channel
    memcpy (&btaddr.serviceClassId, &guidBtSquirt, sizeof (GUID));
    //
    // Connect to remote socket
    //
    rc = connect (t_sock, (struct sockaddr *)&btaddr, sizeof (btaddr));
    if (rc) {
        Add2List (hWnd, TEXT("Connected failed %d"), rc);
        closesocket (t_sock);
        return 0;
    }
    Add2List (hWnd, TEXT("connected..."));

    // Allocate a buffer
    pBuff = (char *)LocalAlloc (LPTR, BUFFSIZE);

    // Send the file name
    // Strip off any leading path, assume len > 1 since we抳e opened file.
    for (i = lstrlen (psfs->szName)-1; (i > 0) && 
                                     (psfs->szName[i] != TEXT ('\\')) ; i--);
    if (psfs->szName[i] == TEXT ('\\')) i++;
    LPTSTR pszNameOnly = &psfs->szName[i];
    // Send name size.
    nCnt = ((lstrlen (pszNameOnly) + 1) * sizeof (WCHAR));
    rc = send (t_sock, (LPSTR)&nCnt, sizeof (nCnt), 0);

    // Send filename.
    if (rc != SOCKET_ERROR) 
        rc = send (t_sock, (LPSTR)pszNameOnly, nCnt, 0);

    if (rc != SOCKET_ERROR)  {
        int nFileSize = GetFileSize (psfs->hFile, NULL);

        // Send file size. Size will always be < 2 gig.
        rc = send (t_sock, (LPSTR)&nFileSize, sizeof (nFileSize), 0);
        if (rc == SOCKET_ERROR) 
            rc = BAD_SOCKET;
        else
            // Recv ack of file size.
            recv (t_sock, (LPSTR)&rc, sizeof (rc), 0);

        // Send the file.
        nTotal = nFileSize;
        while ((!rc) && nFileSize) {

            MySetWindowText (hWnd, TEXT ("%02d%% sent"), 
                             (nTotal-nFileSize)*100/nTotal);
            // Read up to the block size.
            nCnt = min (BLKSIZE, nFileSize);
            ReadFile (psfs->hFile, pBuff, nCnt, (DWORD *)&nBytes, NULL);
            if (nCnt != nBytes) {
                rc = BAD_FILEREAD;
                break;
            }

            // Send the block
            rc = send (t_sock, pBuff, nCnt, 0);
            if (rc == SOCKET_ERROR) {
                Add2List (hWnd, TEXT("send error %d "), GetLastError());
                rc = BAD_SOCKET;
            } else
                Add2List (hWnd, TEXT("sent %d bytes"), rc);
            nFileSize -= rc;

            // Receive ack.
            recv (t_sock, (LPSTR)&rc, sizeof (rc), 0);
        }
        SetWindowText (hWnd, szTitleText);
    }
    // Send close code.
    if (rc != BAD_SOCKET) 
        send (t_sock, (LPSTR)&rc, sizeof (rc), 0);

    // Clean up.
    closesocket (t_sock);
    CloseHandle (psfs->hFile);
    LocalFree (pBuff);  
    LocalFree (psfs);  
    if (rc)
        Add2List (hWnd, TEXT("SendFile Exit rc = %d"), rc);
    else
        Add2List (hWnd, TEXT("File sent successfully."));
    return 0;
}   

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -