Reputation: 6132
I've created a small app which should send a NSString to my server. I've got an application running there, which listens to an extact port and acts like a dumpster: it saves all the data which comes in from there.
The iPhone application I created uses this:
-(IBAction)pressButton:(id)sender {
NSString *iHostname = [NSString stringWithFormat:@"xxx.xxx.xxx.xxx"];
NSString *iPort = [NSString stringWithFormat:@"9100"];
CFWriteStreamRef writeStream;
static const CFOptionFlags kWriteNetworkEvents = kCFStreamEventEndEncountered |
kCFStreamEventErrorOccurred |
kCFStreamEventCanAcceptBytes |
kCFStreamEventOpenCompleted |
kCFStreamEventNone;
CFStreamClientContext ctxt = {0,(void*)NULL,NULL,NULL,NULL};
CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault,(CFStringRef)iHostname);
CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, hostRef, [iPort intValue],
NULL, &writeStream);
CFWriteStreamSetClient(writeStream, kWriteNetworkEvents, WriteStreamClientCallBack, &ctxt);
CFWriteStreamScheduleWithRunLoop(writeStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
So, I call a runloop method:
static void WriteStreamClientCallBack( CFWriteStreamRef stream, CFStreamEventType type, void *clientCallBackInfo ) {
NSLog(@"%lu", type);
switch (type)
{
case kCFStreamEventEndEncountered:
{
NSLog(@"Closing");
CFWriteStreamClose(stream);
break;
}
case kCFStreamEventErrorOccurred:
{
NSLog(@"Crap, error!");
break;
}
case kCFStreamEventCanAcceptBytes:
{
NSLog(@"Stream can accept more bytes");
NSString *reqStr = [NSString stringWithFormat: @"ConReq"];
const UInt8 *rawstring = (const UInt8 *)[reqStr UTF8String];
CFWriteStreamWrite(stream, rawstring, strlen((char *)rawstring));
}
case kCFStreamEventNone:
{
NSLog(@"Nothing is happening");
break;
}
case kCFStreamEventOpenCompleted:
{
NSLog(@"Opened stream!");
break;
}
}
}
Here comes the problem: when I press the button, it stays looped in there. Logging shows case kCFStreamEventCanAcceptBytes
just keeps on getting called. Indeed, when I forcequit the program, the server has received a file with a lot of ConReq
in it. What should I do about it, or what am I doing wrong?
PS. I got the code from here.
Upvotes: 1
Views: 2464
Reputation: 36143
The "can accept" event indicates that, if you have more data to send, you can send (some of) it without blocking. Your problem is you are not tracking how much data you have sent, how much data you have left to send, and whether the socket can currently accept data. Instead, every time there's space to send more data, you send the exact same data every time. It's not much data, so you should expect to quickly see a whole lot of "ready for more data" events.
Upvotes: 1