I'm trying to create Bonjour client and in the process trying to setup input and output streams, I've successfully created the bonjour client, detected them and resolved them. After resolving I'm trying to setup input and output streams but when I tried sending message they do not go. The stream delegates are not getting called either, when I check the stream status it is always 1 (i.e opening), but never changes to open.
Here is what I'm doing to get streams:
-(void)viewDidAppear:(BOOL)animated
{
[self.service getInputStream:&inputStream outputStream:&outputStream];
if(inputStream && outputStream)
{
[outputStream setDelegate:self];
[inputStream setDelegate:self];
[self scheduleInCurrentThread];
[inputStream open];
[outputStream open];
NSLog(#"%lu",(unsigned long)inputStream.streamStatus);
NSLog(#"got Streams");
}
else
{
NSLog(#"failed to acquire streams");
}
}
#pragma mark - schedule in current thread
- (void)scheduleInCurrentThread
{
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
}
P.S: No object is nill.
Related
I have used following code to connect to the server
- (void) initNetworkCommunication
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL,(CFStringRef)URLBASE, 8080, &readStream, &writeStream);
inputStream = (__bridge_transfer NSInputStream *)readStream;
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
// open input and output stream of socket to send and receive data
[inputStream open];
[outputStream open];
}
and following code to send message using output stream
-(IBAction)sendMessage{
if (outputStream.hasSpaceAvailable) {
[outputStream write:[data bytes] maxLength:[data length]];
}
}
but when I try to send message the connection drops and gives connection reset by remote peer.
when I try to send message the connection drops and gives connection
reset by remote peer.
The error text unequivocally states that the peer dropped the connection, so you have to look there for the reason rather than in the code above.
I am using a FTP library for iOS (nkreipke/FTPManager). It works great. I can download a list of directories, upload images, etc.
The problem is that if you leave the app open for like 5 minutes doing nothing and then you try to download or upload, nothing happens.
I've been debugging it and found out that the NSStreamDelegate method - (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent never gets called after that short period of time of being inactive.
Here is the code:
- (NSArray*) _contentsOfServer:(FMServer*)server {
BOOL success = YES;
action = _FMCurrentActionContentsOfServer;
fileSize = 0;
self.directoryListingData = [[NSMutableData alloc] init];
NSURL* dest = [server.destination ftpURLForPort:server.port];
And(success, (dest != nil));
Check(success);
if (![dest.absoluteString hasSuffix:#"/"]) {
//if the url does not end with an '/' the method fails.
//no problem, we can fix this.
dest = [NSURL URLWithString:[NSString stringWithFormat:#"%#/",dest.absoluteString]];
}
CFReadStreamRef readStream = CFReadStreamCreateWithFTPURL(NULL, (__bridge CFURLRef)dest);
And(success, (readStream != NULL));
if (!success) return nil;
self.serverReadStream = (__bridge_transfer NSInputStream*) readStream;
And(success, [self.serverReadStream setProperty:server.username forKey:(id)kCFStreamPropertyFTPUserName]);
And(success, [self.serverReadStream setProperty:server.password forKey:(id)kCFStreamPropertyFTPPassword]);
if (!success) return nil;
self.bufferOffset = 0;
self.bufferLimit = 0;
currentRunLoop = CFRunLoopGetCurrent();
self.serverReadStream.delegate = self;
[self.serverReadStream open];
[self.serverReadStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
CFRunLoopRun(); //<- Hangs here.
And(success, streamSuccess);
if (!success) return nil;
NSArray* directoryContents = [self _createListingArrayFromDirectoryListingData:self.directoryListingData];
self.directoryListingData = nil;
return directoryContents;
serverReadStream is a NSInputStream object.
When the action ends:
if (self.serverReadStream) {
[self.serverReadStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
CFRunLoopStop(CFRunLoopGetCurrent());
self.serverReadStream.delegate = nil;
[self.serverReadStream close];
self.serverReadStream = nil;
}
This code is located at FTPManager.m. I've been looking for answers around the internet but couldn't find any. I don't know why the NSStreamDelegate method gets called when used constantly but after some time of inactivity, it doesn't get called.
It would be nice if someone could help me.
Thanks.
I'm using the same library in my iPad application and I was stuck in the same CFRunLoopRun() call when I was trying to refresh the FTP server content when resuming my application.
I had to do two changes to the FTPManager code.
First, I've changed the order of
[self.serverReadStream open];
[self.serverReadStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
to
[self.serverReadStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.serverReadStream open];
The reason why is that the stream cannot by opened. An error event is raised during the call to open but if the stream is not schedule to the run loop, we will never receive the error event. So scheduling before opening will allow us to get the error event.
The other change which was needed in my case was to disable the persistent connection. It seems that after a suspend/resume cycle of the device, the internal socket used by the stream is getting staled and is always returning an error when trying to access it.
Adding the following line in the stream configuration has solve the issue on my side :
[self.serverReadStream setProperty: (id) kCFBooleanFalse forKey: (id) kCFStreamPropertyFTPAttemptPersistentConnection];
Hope this helps.
I have been doing a client-server communication for a while in iOS but I am here faced to an issue I have some troubles to understand.
I wrote two basic functions: one to send data to the server and the other to receive data from the server. Each one has a parameter called timeout which allows to make the current thread sleep and wake up every 0.25s until the timeout is reached:
-(ReturnCode) send : (NSData*)data :(int)timeOut
{
if(![self isConnectionOpened]) return KO;
float timer = 0;
while(![_outputStream hasSpaceAvailable])
{
[NSThread sleepForTimeInterval:0.25];
timer+=0.25;
if(timer == timeOut) break;
}
int ret = 0;
if([_outputStream hasSpaceAvailable]){
int lg = [data length];
ret = [_outputStream write:[data bytes] maxLength:lg];
if(ret == -1) return KO;
else return OK;
}
return TIMEOUT;
}
- (ReturnCode) receive : (NSData**)data : (int)timeOut : (int)maxLength
{
uint8_t buffer[maxLength];
int len;
NSMutableData* dataReceived = [[NSMutableData alloc] init];
if(! [self isConnectionOpened]) return KO;
float timer = 0;
while(![_inputStream hasBytesAvailable])
{
[NSThread sleepForTimeInterval:0.25];
timer+=0.25;
if(timer == timeOut) break;
}
if(![_inputStream hasBytesAvailable]) return TIMEOUT;
while ([_inputStream hasBytesAvailable]) {
len = [_inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
[dataReceived appendBytes:buffer length:len];
*data = dataReceived;
return OK;
}
}
return KO;
}
With iPhone 4 + iOS6, everything is going fine. But under iOS7, for some fuzzy reasons, inputstream and outputstream are closing prematurely (NSStreamEventErrorOccurred raised). The fact is, if I put a breakpoint just before receiving data from server and make the code run, it works fine and reading/writing streams dont close wrongly.
So I think there is a synchronisation problem but I dont understand why... If anyone has ideas, pls help...
I found where my issue was coming from.
Actually, be really careful on where are scheduled inputstream and outputstream. Indeed, I was told that Apple objects had to be executed on main thread, so I scheduled them this way:
dispatch_async(dispatch_get_main_queue(), ^ {
[_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_inputStream open];
[_outputStream open];
});
But actually, it seems better to schedule them on the current loop from the current thread, and not dispatching the schedule action on main thread:
[_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_inputStream open];
[_outputStream open];
I have an application that connects users to a serve. Users can connect to a host to communicate inserting an IP address and communicate using NSStream. Pressing the connect button starts a connection to the host and the user can receive and send messages.
I want to give a user the ability to disconnect from the server to not listen to pressing a disconnect button. The problem is that I am never able to successfully close the stream.
This is my current implementation:
// Create connection "Connect Button"
- (void)initNetworkCommunication:(UIViewController *)sender {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)#"123.456.789.123", 80, &readStream, &writeStream);
inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
controller = sender;
}
// Stop connection "Disconnect Button"
- (void)stopNetworkConnection {
[inputStream close];
[outputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream release];
[outputStream release];
inputStream = nil;
outputStream = nil;
NSLog(#"Disconnect from stream");
}
The flow of operations is as follows:
User insert a valid IP address;
User press "Connect Button";
Everything works fine, connection established and user can send/receive messages;
User press "Disconnect Button" and user do not receive messages;
User press "Connect Button" but no longer able to connect
I tried this solution but it did not work:
NSStream closing and opening error
Thanks in advance for the help
I have a VoIP app that uses a TCP service to wake it up on incoming calls.
The TCP socket is created with this code fragment:
CFReadStreamRef read = NULL;
CFWriteStreamRef write = NULL;
...
CFStreamCreatePairWithSocketToHost(NULL,(__bridge CFStringRef)shost, port, &read, &write);
self.read = (__bridge NSInputStream*)read;
self.write = (__bridge NSOutputStream*)write;
if (![self.read setProperty:NSStreamNetworkServiceTypeVoIP
forKey:NSStreamNetworkServiceType]){
[Log log:#"Could not set VoIP mode to read stream"];
}
if (![self.write setProperty:NSStreamNetworkServiceTypeVoIP
forKey:NSStreamNetworkServiceType]){
[Log log:#"Could not set VoIP mode to write stream"];
}
self.read.delegate = self;
self.write.delegate = self;
CFRelease(read);
CFRelease(write);
[self.read scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[self.write scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[self.read open];
[self.write open];
I've also set the following:
VoIP & Audio in the info plist
Keep alive timer using [UIApplication sharedApplication] setKeepAliveTimeout
UIRequiresPersistentWiFi = YES in the info plist (quite sure it's not required, but...)
This works well while the app is in the foreground, and even works well in the background for a few minutes, but after a few minutes - the app does not receive any new TCP messages.
It doesn't work on wifi or 3G, same result for both.
I also tried setting the property just to the read stream (though the read and write point to the same socket).
Whenever I receive data on the TCP or send data I also start a short background task.
BTW - everything takes place on the main thread.
I've checked if the app crashes - it doesn't.
The same behavior can be observed while debugging on the device - after a while - nothing is received (no crashes, warnings, anything).
What am I doing wrong?
Looks like your code should work. But there may be two technical problems I can think of:
If you try this from LAN connection, while app in background the LAN router can close passive TCP connection because, in this case, SIP stack(guess you use SIP protocol) can't send data keep alive every 15 to 30 secs like it would in foreground.
Less likely, suppose you know what you doing, but since registration keep alive can be triggered only once in 10 minutes while in background, make sure that SIP server allows such a long expire period and you define it right in registration message.
Try the following code.Make sure you have only one voip socket in your app.
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)#"1.2.3.4",9999, &readStream, &writeStream);
CFReadStreamSetProperty(readStream,kCFStreamNetworkServiceType,kCFStreamNetworkServiceTypeVoIP);
CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
inputStream = (NSInputStream *)readStream;
[inputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
outputStream = (NSOutputStream *)writeStream;
[outputStream setDelegate:self];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream open];
In ViewController.h file add
#property (nonatomic, strong) NSInputStream *inputStream;
#property (nonatomic, strong) NSOutputStream *outputStream;
#property (nonatomic) BOOL sentPing;
In ViewController.m file add after #implementation ViewController
const uint8_t pingString[] = "ping\n";
const uint8_t pongString[] = "pong\n";
Add following code in viewDidLoad
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)(#"192.168.0.104"), 10000, &readStream, &writeStream);
//in above line user your MAC IP instead of 192.168.0.104
self.sentPing = NO;
//self.communicationLog = [[NSMutableString alloc] init];
self.inputStream = (__bridge_transfer NSInputStream *)readStream;
self.outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[self.inputStream setProperty:NSStreamNetworkServiceTypeVoIP forKey:NSStreamNetworkServiceType];
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[self.outputStream open];
//After every 10 mins this block will be execute to ping server, so connection will be live for more 10 mins
[[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{
if (self.outputStream)
{
[self.outputStream write:pingString maxLength:strlen((char*)pingString)];
//[self addEvent:#"Ping sent"];
}
}];
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
switch (eventCode) {
case NSStreamEventNone:
// do nothing.
break;
case NSStreamEventEndEncountered:
//[self addEvent:#"Connection Closed"];
break;
case NSStreamEventErrorOccurred:
//[self addEvent:[NSString stringWithFormat:#"Had error: %#", aStream.streamError]];
break;
case NSStreamEventHasBytesAvailable:
if (aStream == self.inputStream)
{
uint8_t buffer[1024];
NSInteger bytesRead = [self.inputStream read:buffer maxLength:1024];
NSString *stringRead = [[NSString alloc] initWithBytes:buffer length:bytesRead encoding:NSUTF8StringEncoding];
stringRead = [stringRead stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
//[self addEvent:[NSString stringWithFormat:#"Received: %#", stringRead]];
//if server response is 'call' then a notification will go to notification center and it will be fired
//immediately and it will popup if app is in background.
if ([stringRead isEqualToString:#"call"])
{
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = #"New VOIP call";
notification.alertAction = #"Answer";
//[self addEvent:#"Notification sent"];
[[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}
//else if ([stringRead isEqualToString:#"ping"])
//{
//if server response is 'ping' then a sting 'pong' will go to server immediately
//[self.outputStream write:pongString maxLength:strlen((char*)pongString)];
//}
}
break;
case NSStreamEventHasSpaceAvailable:
if (aStream == self.outputStream && !self.sentPing)
{
self.sentPing = YES;
if (aStream == self.outputStream)
{
[self.outputStream write:pingString maxLength:strlen((char*)pingString)];
//[self addEvent:#"Ping sent"];
}
}
break;
case NSStreamEventOpenCompleted:
if (aStream == self.inputStream)
{
//[self addEvent:#"Connection Opened"];
}
break;
default:
break;
}
}
Build your app and run
Open terminal in your MAC PC and write nc -l 10000 and press enter
$ nc -l 10000
Then write call and press enter