我正在使用 Winsocket 为类编写一个小型服务器/客户端文件传输,它基本上可以工作,只是在我收到文件并将其写入我的硬盘后,我无法在套接字上接收更多消息。
传输代码如下所示:
long size = GetFileSize(hFile, NULL);
TransmitFile(_socket, hFile, size, 0, NULL, NULL, TF_DISCONNECT);
ok = ::recv(_socket, cantwortfilename, 100, 0); // getting a confirmation (1)
cantwortfilename[ok] = '\0';
cout << cantwortfilename << endl;
char test[] = "ok!";
::send(_socket, test, strlen(test), 0); // to test if server receives again (2)
我用 0 而不是 size 尝试了它,结果相同。
现在到服务器端的接收:
HANDLE hFile = CreateFile(filepathlong, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
while (1)
{
ReadFile((HANDLE)_socket, &buffer, MAX_PATH, &dwbr, &AsyncInfo);
GetOverlappedResult((HANDLE)_socket, &AsyncInfo, &dwbr, TRUE);
if (dwbr == 0) break;
WriteFile(hFile, buffer, dwbr, &dwbr, NULL);
}
char test[] = "alles ok!";
::send(_socket, test, strlen(test), 0); // sending the confirmation (1)
CloseHandle(hFile);
i = ::recv(_socket, test, 10, 0); // receiving the test (2)
test[i] = '\0';
cout << "empfangen:" << test << endl;
据我所知,文件的传输工作正常(试过 rar jpg .h)和
::send(_socket, test, strlen(test), 0); // sending the confirmation (1)
出去也很好。
但是在那之后的接收什么也没给我?还是空的?我猜是空的,因为 recv 也不会阻止程序。但是当我给出它时,“i”将为0。
为了检查我是否在 while(1) 循环中犯了某种错误,我尝试了另一种方式来接收文件。
第二次尝试:
int r;
ofstream file(filepath, std::ios::out | std::ios::binary | std::ios::trunc);
char *memblock;
int size = 7766; // was the size of the file i was testing with
memblock = new char[size];
memset(memblock, 0, size);
if (file.is_open()){
//while memory blocks are still being received
while ((r = recv(_socket, memblock, 256, 0)) != 0)
{
//if there's a socket error, abort
if (r == SOCKET_ERROR)
{
cout << "error" << endl;
}
//write client's file blocks to file on server
file.write(memblock, r);
}
delete[] memblock;
//finished sending memory blocks; file is completely transferred.
file.close();
}
之后,再次发送具有相同结果的recv。该文件有效,但再次接收让我有些空虚。
那么谁能告诉我为什么以及如何解决这个问题?如果可能的话,尽可能少的改变?
谢谢,马丁
编辑:现在为我工作的代码:
char csize[256];
rc = recv(_socket, csize, 256, 0);
csize[rc] = '\0';
int size = atoi(csize);
int bytes_read = 0, len = 0;
int r;
ofstream file(filepath, std::ios::out | std::ios::binary | std::ios::trunc);
char *memblock;
memblock = new char[size];
memset(memblock, 0, size);
if (file.is_open()){
while (bytes_read < size){
len = recv(_socket, memblock + bytes_read, size - bytes_read, 0);
bytes_read += len;
}
file.write(memblock, size);
delete[] memblock;
file.close();
}