how can i send a text to another device only after receiver side instream and outstream setup is done?
i created a network Application to transfer text message between two devices through WiFi network.when i select a device to pair there is a delegate called "TCPServerAcceptCallBack" will trigger in receiver side and it will setup the input and output streams. but it will take milliseconds to do the setup of streams.whenever i am sending a data from my device there is checking of [_outStream hasSpaceAvaila开发者_如何学Goble].i mentioned that instream and outstream setup in receiver side will take milliseconds .so first time the condition will false.i used while loop to stop doing send method before setup is done.but there is a problem that when execution in while loop there is a chance to connection lose in receiver side and also not confident with while loop. next i created a sleep of 3 millisecond ,it working fine but there is chance of occur error when network is very slow. i am planning to trigger a delegate from receiver side to sender device at the time of instream and outstream setup is done.so please tell me how can do it (or) provide me any other good way to solve this problem...
My Code...receiver side case NSStreamEventHasBytesAvailable: { if (stream == _inStream) { // read it in unsigned int len = 0;
//here the length is assigning..i can send text files only after this below statement is executed.but it will take few minitus. len = [_inStream read:buf maxLength:buffSize]; buf[len] = '\0'; if(!len) { if ([stream streamStatus] != NSStreamStatusAtEnd) NSLog(@"Failed reading data from peer"); } else { NSString *message = [NSString stringWithUTF8String:(char *)buf];
//Display image from app bundle
NSString *path=[[NSBundle mainBundle] pathForResource:message ofType:@"png"];
if(path !=nil)
{
[imageView setImage:[UIImage imageWithContentsOfFile:path]];
}
else
{
UIImage *image = [UIImage imageNamed:@"no_image.png"];
[imageView setImage:image];
}
// here you do whatever you need with your received NSString *message
[txtUserInput setText:message];
}
}
break;
Sender part..
[- (void) sendText:(NSString *)string { const uint8_t *message = (const uint8_t *)[string UTF8String]; //waiting up to outStream hasSpaceAvailable while (![_outStream hasSpaceAvailable]) { continue; } //once outStream hasSpaceAvailable it will send datas. if (_outStream && [_outStream hasSpaceAvailable]) if([_outStream write:message maxLength:strlen((char *)message)] == -1) NSLog(@"Failed sending data to peer"); } @end
Don't use a while loop,that's just wasting CPU cycles. Do it in the callback.
精彩评论