Windows で Winsock2 を使用してネットワーク経由でデータを受信するのに問題があります。シンプルなクライアントとサーバー システムを使用して、ファイル転送プログラムを実装しようとしています。現在のコードでは、バッファのサイズではないため、最後に受信したパケットはファイルに追加されません。そのため、ファイル転送は完全には完了せず、エラーが発生して中断します。常に最後のパケットではなく、それより前の場合もあります。
サーバー コードのスニペットを次に示します。
int iResult;
ifstream sendFile(path, ifstream::binary);
char* buf;
if (sendFile.is_open()) {
printf("File Opened!\n");
// Sends the file
while (sendFile.good()) {
buf = new char[1024];
sendFile.read(buf, 1024);
iResult = send(AcceptSocket, buf, (int)strlen(buf)-4, 0 );
if (iResult == SOCKET_ERROR) {
wprintf(L"send failed with error: %d\n", WSAGetLastError());
closesocket(AcceptSocket);
WSACleanup();
return 1;
}
//printf("Bytes Sent: %d\n", iResult);
}
sendFile.close();
}
クライアント コードのスニペットは次のとおりです。
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
char recvbuf[DEFAULT_BUFLEN] = "";
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0){
printf("%s",recvbuf);
myfile.write(recvbuf, iResult);
}
else if ( iResult == 0 ) {
wprintf(L"Connection closed\n");
} else {
wprintf(L"recv failed with error: %d\n", WSAGetLastError());
}
} while( iResult > 0 );
myfile.close();
辞書であるファイルを転送しようとすると、ランダムに壊れることがあります。たとえば、ある実行は S の早い段階で壊れ、末尾に奇妙な文字が追加されましたが、これは珍しいことではありません。
...
sayable
sayer
sayers
sayest
sayid
sayids
saying
sayings
╠╠╠╠╠╠╠╠recv failed with error: 10054
これらのエラーや奇妙な文字を処理するにはどうすればよいですか?