Reputation: 227
I am using tcp connection to connect a server using ip and port. I can write and read stream on it. my problem is when I turn off server .app stop with "EXC_BAD_ACCESS" can anyone help me?
this is connect code:
-(void) connectToServerUsingStream:(NSString *)urlStr
portNo: (uint) portNo {
if (![urlStr isEqualToString:@""])
{
NSURL *website = [NSURL URLWithString:urlStr];
if (!website)
{
NSLog(@"%@ is not a valid URL");
return;
}
else
{
[NSStream getStreamsToHostNamed:urlStr
port:portNo
inputStream:&iStream
outputStream:&oStream];
[iStream retain];
[oStream retain];
[iStream setDelegate:self];
[oStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[oStream open];
[iStream open];
}
}
}
and this is stream event delegate:
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
if (data == nil)
{
data = [[NSMutableData alloc] init];
}
uint8_t buf[1024];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buf maxLength:1024];
if(len)
{
[data appendBytes:(const void *)buf length:len];
int bytesRead;
bytesRead += len;
}
else
{
NSLog(@"No data.");
return;
}
NSString *str = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(@"From server: %@",str);
[str release];
[data release];
data = nil;
break;
}
case NSStreamEventErrorOccurred:
{
NSError *theError = [stream streamError];
NSLog(@"Error reading stream! ,Error %i: %@",[theError code], [theError localizedDescription]);
[self disconnect];
[self connectToServerUsingStream:kHostIP portNo:kPort];
break;
}
case NSStreamEventHasSpaceAvailable:
{
if(stream == oStream && !isDataSent)
{
isDataSent = YES;
[self writeToServer:@"HI"];
}
break;
}
}
}
Upvotes: 2
Views: 3085
Reputation: 8845
Try adding the following linker flags:
OTHER_LDFLAGS = -lz -lxml2 -ltidy -ObjC
To your project.
Upvotes: 0
Reputation: 11
You should probably implement NSStreamEventEndEncountered case and close / release the stream.
Upvotes: 1
Reputation: 4276
What logging messages are you getting so you can see which parts of your code get called?
Have you tried setting some breakpoints and then stepping through to see the exact point of failure and also then inspect the objects in case you aren't retaining/releasing properly?
What other debugging steps have you taken so far?
Upvotes: 0