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);
}