我正在为音乐共享应用程序编写网络服务器......当我有一个大文件(即 mp3)时,这不起作用。它在 SIGPIPE 错误代码上崩溃。我发送的标题有“连接:关闭”——但我认为这会等到下载完成后关闭连接。我知道这可能应该被分叉到一个线程中,但为了测试我想让它同步工作。
NSData *fileData =[NSData dataWithContentsOfFile:filePath];
CFHTTPMessageRef response =
CFHTTPMessageCreateResponse(
kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1);
CFHTTPMessageSetHeaderFieldValue(
response, (CFStringRef)@"Content-Type", (CFStringRef)@"audio/mpeg");
CFHTTPMessageSetHeaderFieldValue(
response, (CFStringRef)@"Connection", (CFStringRef)@"close");
CFHTTPMessageSetHeaderFieldValue(
response,
(CFStringRef)@"Content-Length",
(CFStringRef)[NSString stringWithFormat:@"%ld", [fileData length]]);
CFDataRef headerData = CFHTTPMessageCopySerializedMessage(response);
@try
{
[fileHandle writeData:(NSData *)headerData];
[fileHandle writeData:fileData];
}@catch (NSException *exception)
{
// Ignore the exception, it normally just means the client
// closed the connection from the other end.
}