Creating a socket connection and sending some data over the socket connection is pretty simple.
Configuring the connection
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.1.6",5060, &readStream, &writeStream);
self.inputStream = (__bridge_transfer NSInputStream *)readStream;
self.outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[self.inputStream setProperty:NSStreamNetworkServiceTypeVoIP forKey:NSStreamNetworkServiceType];
// Setting the self delegate in input/output stream
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
// Open the Connection
[self.inputStream open];
[self.outputStream open];
Handlign callbacks
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
switch (eventCode) {
case NSStreamEventNone:
break;
case NSStreamEventEndEncountered:
[self printLog:@"Stream Event End"];
break;
case NSStreamEventErrorOccurred:
[self printLog:[NSString stringWithFormat:@"Stream error: %@", aStream.streamError]];
break;
case NSStreamEventHasBytesAvailable:
if (aStream == self.inputStream)
{
uint8_t buffer[1024];
uint8_t *pongString = (uint8_t *)"Plong!\r\n";
NSInteger bytesRead = [self.inputStream read:buffer maxLength:1024];
NSString *stringRead = [[NSString alloc] initWithBytes:buffer length:bytesRead encoding:NSUTF8StringEncoding];
stringRead = [stringRead stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
[self printLog:[NSString stringWithFormat:@"Received: %@", stringRead]];
[self.outputStream write:pongString maxLength:strlen((char*)pongString)];
}
break;
case NSStreamEventHasSpaceAvailable:
if (aStream == self.outputStream)
{
if (aStream == self.outputStream)
{
[self.outputStream write:(const uint8_t *)"Plong!\r\n" maxLength:strlen("Plong\r\n")];
[self printLog:@"Plong sent"];
}
}
break;
case NSStreamEventOpenCompleted:
if (aStream == self.inputStream)
{
[self printLog:@"NSStreamEventOpenCompleted"];
}
break;
default:
break;
}
}
References: