iPhone에서 클라이언트를 프로그래밍 중입니다. 일부 문자열을 보내고 서버에서 이미지를 수신하고 싶습니다.iPhone에서 이미지 받기 (TCP 클라이언트)
이 튜토리얼 (http://www.devx.com/wireless/Article/43551)이 매우 유용합니다. 문자열 수신을 원한다면 작동하지만 이미지를 받고 싶습니다. 작동하지 않을 수 있습니다.
iPhone이 데이터를 수신 할 때의 코드입니다.
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventHasBytesAvailable: {
if (data == nil) {
data = [[NSMutableData alloc] init];
}
uint8_t buf[102400];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buf maxLength:102400];
if(len) {
[data appendBytes:(const void *)buf length:len];
// Recibir img
uint8_t size; // Let's make sure size is an explicit width.
NSInteger totalBytesRead = 0;
NSInteger bytesRead = [iStream read: &size maxLength: sizeof size];
while (bytesRead > 0 && totalBytesRead + bytesRead < sizeof size) {
totalBytesRead+= bytesRead;
bytesRead = [iStream read: &size + totalBytesRead maxLength: (sizeof size) - totalBytesRead];
}
if (bytesRead >= 0) {
totalBytesRead += bytesRead;
}
else {
// read failure, report error and bail
}
if (totalBytesRead < sizeof size) {
// connection closed before we got the whole size, report and bail
}
size = ntohl(size); // assume wire protocol uses network byte ordering
NSMutableData* buffer = [[NSMutableData alloc] initWithLength: size];
totalBytesRead = 0;
bytesRead = [iStream read: [buffer mutableBytes] maxLength: size];
while (bytesRead > 0 && totalBytesRead + bytesRead < size) {
totalBytesRead+= bytesRead;
bytesRead = [iStream read: [buffer mutableBytes] + totalBytesRead maxLength: size - totalBytesRead];
}
if (bytesRead >= 0) {
totalBytesRead += bytesRead;
}
else {
// read failure, report error and bail (not forgetting to release buffer)
}
if (totalBytesRead < size) {
// connection closed before we got the whole image, report and bail (not forgetting to release buffer)
}
else {
[buffer setLength: size];
}
imgResultado.image = [UIImage imageWithData: buffer];
[buffer release];
[data release];
data = nil;
}
else {
NSLog(@"No data.");
}
} break;
}}
그것은 작동하지 않습니다는 ... 당신이 나를 도울 수 :이 튜토리얼과 JeremyP (http://stackoverflow.com/questions/4613218)에서이 답변으로 만든 혼합입니까? 당신이 원하는 모든 표시 할 서버에서 이미지를 다운로드하는 경우
이것은 이전 코드가 예상했던 것처럼 서버가 스트림 시작 부분에서 크기 정수를 전송하지 않는다는 것을 의미합니다. 이것이 이미지 데이터 인 경우 처음 4 바이트를 효과적으로 삭제했기 때문에 이전 코드가 작동하지 않는 이유입니다. – kamprath
이 코드를 사용하면 이미지를 최대 1000000 바이트까지받을 수 있습니다. 거의 1MB입니까? (귀하의 원래 코드는 약 100k에 불과 했습니까?) 확인을 시도하십시오. – user523234
user523234 예, 클라이언트는 최대 1000000 바이트의 이미지를 수신 할 수 있습니다. 클레어웨어는 좋은 설명이 될 수 있습니다. 나는 당신이 옳다고 생각합니다. 그 방법은 내 대답보다 안전하지만 사용하고 싶다면 서버를 수정해야합니다. – Xithias