CREATE AND MANAGE SOCKET CONNECTION

Delegate Used: NSStreamDelegate

Setup and Close

#pragma mark – Setup and Close

– (void)chatServerSetup {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)kChatServerHost, kChatServerPort, &readStream, &writeStream);

inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}

– (void)chatServerClose {
[inputStream close];
[outputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream setDelegate:nil];
[outputStream setDelegate:nil];

isConnected = FALSE;
isSubscribed = FALSE;
}

Handle Event & Receive Message (Delegate Method)

– (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{

switch (streamEvent) {
case NSStreamEventOpenCompleted:
isConnected = TRUE;
break;

case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
NSUInteger len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
[self messageReceived:output];
}
}
}
}
break;

case NSStreamEventErrorOccurred:
NSLog(@”Can not connect to the host!”);
[self chatServerClose];
break;

case NSStreamEventEndEncountered:
[self chatServerClose];
break;

case NSStreamEventHasSpaceAvailable:
NSLog(@”Listening…”);
break;

default:
NSLog(@”Unknown event”);
}
}

 

Send Message

NSData *data = [msgToSend dataUsingEncoding:NSUTF8StringEncoding];
[outputStream write:[data bytes] maxLength:[data length]];

CREATE AND MANAGE SOCKET CONNECTION