如何在 Cocoa 套接字中发送格式正确的 HTTP 响应?
我正在制作一个包含内置 HTTP 服务器的应用程序。我需要通过套接字发送 PNG 图像,但不知何故它变得混乱并且图像不显示。这是我的代码(我正在使用 AsyncSockets):
if(processingURL == FALSE) {
NSString *filePath = [[NSString alloc] initWithFormat:@"%@/Contents/Resources/public%@",[self getApplicationPath], [request objectAtIndex:1]];
//NSLog(@"%@", filePath);
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
contententType = @"image/png";
responseCode = @"200 OK";
// responseBody = [[NSString alloc] initWithData:[[NSFileManager defaultManager] contentsAtPath:filePath] encoding:NSASCIIStringEncoding];
NSData * content = [[NSData alloc] initWithContentsOfFile:filePath];
responseBody = [[NSString alloc] initWithData:content encoding:NSASCIIStringEncoding];
NSLog(@"%@",responseBody);
}
}
data = [[NSString stringWithFormat:@"HTTP/1.1 %@\nContent-Type: %@\n\n\n %@", responseCode, contententType, responseBody] dataUsingEncoding:NSUTF8StringEncoding];
[sock writeData:data withTimeout:-1 tag:0];
我做错了什么?我认为问题在于响应,格式错误,但我不知道,谢谢:)
I'm making an app which includes a built in HTTP server. I need to send a PNG image over the socket, but somehow it's getting messed and the image just doesn't shows up. This is my code (I'm using AsyncSockets):
if(processingURL == FALSE) {
NSString *filePath = [[NSString alloc] initWithFormat:@"%@/Contents/Resources/public%@",[self getApplicationPath], [request objectAtIndex:1]];
//NSLog(@"%@", filePath);
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
contententType = @"image/png";
responseCode = @"200 OK";
// responseBody = [[NSString alloc] initWithData:[[NSFileManager defaultManager] contentsAtPath:filePath] encoding:NSASCIIStringEncoding];
NSData * content = [[NSData alloc] initWithContentsOfFile:filePath];
responseBody = [[NSString alloc] initWithData:content encoding:NSASCIIStringEncoding];
NSLog(@"%@",responseBody);
}
}
data = [[NSString stringWithFormat:@"HTTP/1.1 %@\nContent-Type: %@\n\n\n %@", responseCode, contententType, responseBody] dataUsingEncoding:NSUTF8StringEncoding];
[sock writeData:data withTimeout:-1 tag:0];
What I'm doing wrong? I think the problem is the response, which is malformed, but I don't know, thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要将任意文件内容数据视为文本。事实并非如此。
PNG 不是 ASCII 文本文件;它包含您必须如此对待的二进制数据。这意味着始终使用 NSData,而不是在任何时候尝试将其转换为或解释为 NSString 的文本。
您应该创建的唯一字符串是响应代码和标头。从该字符串生成数据,然后将文件中的数据连接到该字符串上并将其发送到服务器。
Don't treat arbitrary file-contents data as text. It isn't.
A PNG is not an ASCII text file; it contains binary data that you must treat as such. That means staying with NSData the whole way through, and not at any point trying to convert it into or interpret it as text for an NSString.
The only string you should create is for the response code and headers. Generate data from that string, then concatenate the data from the file onto it and send that to the server.