iPhoneでクライアントをプログラミングしています。私はいくつかの文字列を送信し、サーバーからイメージを受信したい。iPhone(TCPクライアント)で画像を受信
私はこのチュートリアル(http://www.devx.com/wireless/Article/43551)を見つけました。とても役に立ちました。文字列を受け取りたい場合には機能しますが、今はイメージを受け取りたいと思っています。それを動作させることはできません。
iPhoneがデータを受信したときのコードです。それはJeremyPから(http://stackoverflow.com/questions/4613218)チュートリアルとこの答えで作られたミックスです:
- (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;
}}
それは動作しません...あなたは私を助けることができますか?
これは、以前のコードが予期していたように、サーバーがストリームの先頭にサイズの整数を送信していないことを意味します。画像データの場合、最初の4バイトを効果的に削除したため、前のコードが機能しませんでした。 – kamprath
このコードでは、1000000バイトまでの画像を受信できます。それはほぼ1MBですか? (あなたの元のコードは約100kしか持っていませんでしたか?)ただ確認してみてください... – user523234
user523234はい、クライアントは最大1000000バイトの画像を受信できます。 Claireware、それは良い説明かもしれない、私はあなたが正しいと思う。その方法は私の答えよりも安全ですが、私がそれを使いたい場合は、サーバーを変更する必要があります。 – Xithias