对于我大学的一个项目,我必须创建一个客户端/服务器应用程序,其中客户端和服务器通过套接字通信,客户端使用DirectSound API从服务器流式传输WAV文件
当我试图播放WAV文件时,我收到此错误“创建临时文件时出错”
这是创建临时文件的代码
// Receive the list of files from the server
char buffer[256] = { 0 };
int bytes_received = recv(socket_client, buffer, sizeof(buffer), 0);
if (bytes_received == SOCKET_ERROR) {
std::cout << "Error receiving file list" << std::endl;
closesocket(socket_client);
WSACleanup();
return 1;
}
std::string file_list(buffer, bytes_received);
std::cout << "Available files: " << std::endl << file_list << std::endl;
// Ask the user to choose a file
std::string chosen_file;
std::cout << "Enter the name of the file you want to play: ";
std::cin >> chosen_file;
// Send the chosen file to the server
if (send(socket_client, chosen_file.c_str(), chosen_file.size(), 0) == SOCKET_ERROR) {
std::cout << "Error sending chosen file" << std::endl;
closesocket(socket_client);
WSACleanup();
return 1;
}
// Receive the file size from the server
int file_size;
if (recv(socket_client, reinterpret_cast<char*>(&file_size), sizeof(file_size), 0) == SOCKET_ERROR) {
std::cout << "Error receiving file size" << std::endl;
closesocket(socket_client);
WSACleanup();
return 1;
}
// Create a temporary file to store the received data
std::string file_path = "path/to/temp/file.wav";
std::ofstream temp_file(file_path, std::ios::binary);
if (!temp_file.is_open()) {
std::cout << "Error creating temp file" << std::endl;
closesocket(socket_client);
WSACleanup();
return 1;
}
// Receive the file from the server in chunks
const int CHUNK_SIZE = 1024;
char chunk[CHUNK_SIZE];
int total_bytes_received = 0;
while (total_bytes_received < file_size) {
bytes_received = recv(socket_client, chunk, CHUNK_SIZE, 0);
if (bytes_received == SOCKET_ERROR) {
std::cout << "Error receiving file" << std::endl;
temp_file.close();
closesocket(socket_client);
WSACleanup();
return 1;
}
temp_file.write(chunk, bytes_received);
total_bytes_received += bytes_received;
}
temp_file.close();
std::cout << "File received: " << chosen_file << std::endl;
1条答案
按热度按时间juud5qan1#
错误“创建临时文件时出错”表示在播放之前创建临时文件以存储接收到的WAV文件时出现问题。此错误可能由多种原因导致,例如没有权限写入创建临时文件的目录,或者为临时文件指定的文件路径有问题。
可能是因为客户端没有正确接收到文件大小,所以没有创建临时文件。您可以检查变量'file_size'的值是否正确。如果recv()函数无法检索到正确的文件大小,则其余代码将无法按预期工作。
也可能是客户端无法从服务器接收文件列表,因此出现错误消息“接收文件列表时出错”。检查'bytes_received'变量的值,确认该值不等于SOCKET_ERROR。
此外,检查send()函数的返回值也很有帮助,这样可以确保客户端将所选文件的名称正确地发送到服务器。
您可以在代码中添加一些调试语句,以帮助您了解可能导致错误的原因。您还可以查看windows事件查看器以获取有关错误的详细信息。