TransmitFile使用(发送文件)(转)
BOOL TransmitFile( SOCKET hSocket, HANDLE hFile, DWORD nNumberOfBytesToWrite, DWORD nNumberOfBytesPerSend, LPOVERLAPPED lpOverlapped, LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers, DWORD dwFlags ); 参数: hSocket 面向连接的SOCKET句柄。 hFile 已打开的文件句柄 nNumberOfBytesToWrite 要传送的字节数。0值表示传送整个文件。 nNumberOfBytesPerSend 每次传送的数据块的大小。0值表示使用SOCKET LAYER的默认值。 lpOverlapped 指向OVERLAPPED结构的指针。NULL值表示不开启overlapped I/O模式。 lpTransmitBuffers 指向TRANSMIT_FILE_BUFFERS结构指针。NULL值表示仅仅传输文件。 dwFlags 有三个值可选TF_DISCONNECT TF_REUSE_SOCKET TF_WRITE_BEHIND 给出接收端的代码: SOCKET socketListen = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); bind(socketListen,NULL,0); listen(socketListen,SOMAXCONN); SOCKET socketRead = accept(socketListen,NULL,0); char sz[1000000]; while(true) { if(recv(socketRead,sz,strlen(sz))==SOCKET_ERROR ) break; //写入文件 } 发送端代码 connect... TransmitFile(hSocket,hFile,0,0,0,NULL,TF_DISCONNECT ); //使用例子 //发送端 //发送文件 HANDLE hFile = CreateFile(lpszFilePath,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); TransmitFile(m_Socket,hFile,0,TRANS_FILE_LENGTH,NULL,NULL,TF_DISCONNECT); CloseHandle(hFile); //接收端 ULONG lReadSize = 0; char szInfo[TRANS_FILE_LENGTH] = {0}; HANDLE hFile = CreateFile(lpszFilePah,GENERIC_WRITE,FILE_SHARE_WRITE,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0); while (hFile != INVALID_HANDLE_VALUE) { int iSize = recv(m_Socket,szInfo,TRANS_FILE_LENGTH,0); if(iSize==SOCKET_ERROR||iSize==0) { CloseHandle(hFile); break; } else if(iSize<TRANS_FILE_LENGTH) { WriteFile(hFile,szInfo,iSize,&lReadSize,NULL); CloseHandle(hFile); break; } //写入文件 WriteFile(hFile,szInfo,iSize,&lReadSize,NULL); }