This guide is based on the excellent Ray Wenderlick guide
Adding A TCP Client To A ViewController Class
In your #ViewController.h
#import
@interface MyViewController : UIViewController
<NSStreamDelegate> //-ADD THIS
{
NSInputStream *InputStream;
NSOutputStream *OutputStream;
NSMutableData *OutputData;
}
- (void)TcpClientInitialise;
@end
In your #ViewController.m
//**************************************
//**************************************
//********** VIEW WILL APPEAR **********
//**************************************
//**************************************
//View about to be added to the window (called each time it appears)
//Occurs after other view's viewWillDisappear
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self TcpClientInitialise];
}
//*******************************************
//*******************************************
//********** TCP CLIENT INITIALISE **********
//*******************************************
//*******************************************
- (void)TcpClientInitialise
{
NSLog(@"Tcp Client Initialise");
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"1.2.3.4", 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];
}
//**********************************
//**********************************
//********** SENDING DATA **********
//**********************************
//**********************************
NSString *response = @"HELLO1234";
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[OutputStream write:[data bytes] maxLength:[data length]]; //<<Returns actual number of bytes sent - check if trying to send a large number of bytes as they may well not have all gone in this write and will need sending once there is a hasspaceavailable event
//****************************************
//****************************************
//********** TCP CLIENT RECEIVE **********
//****************************************
//****************************************
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)StreamEvent
{
switch (StreamEvent)
{
case NSStreamEventOpenCompleted:
NSLog(@"TCP Client - Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == InputStream)
{
uint8_t buffer[1024];
int 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)
{
NSLog(@"TCP Client - Server sent: %@", output);
}
//Send some data (large block where the write may not actually send all we request it to send)
int ActualOutputBytes = [OutputStream write:[OutputData bytes] maxLength:[OutputData length]];
if (ActualOutputBytes >= ChunkToSendLength)
{
//It was all sent
[OutputData release];
OutputData = nil;
}
else
{
//Only partially sent
[OutputData replaceBytesInRange:NSMakeRange(0, ActualOutputBytes) withBytes:NULL length:0]; //Remove sent bytes from the start
}
}
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"TCP Client - Can't connect to the host");
break;
case NSStreamEventEndEncountered:
NSLog(@"TCP Client - End encountered");
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
break;
case NSStreamEventNone:
NSLog(@"TCP Client - None event");
break;
case NSStreamEventHasSpaceAvailable:
NSLog(@"TCP Client - Has space available event");
if (OutputData != nil)
{
//Send rest of the packet
int ActualOutputBytes = [OutputStream write:[OutputData bytes] maxLength:[OutputData length]];
if (ActualOutputBytes >= [OutputData length])
{
//It was all sent
[OutputData release];
OutputData = nil;
}
else
{
//Only partially sent
[OutputData replaceBytesInRange:NSMakeRange(0, ActualOutputBytes) withBytes:NULL length:0]; //Remove sent bytes from the start
}
}
break;
default:
NSLog(@"TCP Client - Unknown event");
}
}
//*****************************************
//*****************************************
//********** VIEW WILL DISAPPEAR **********
//*****************************************
//*****************************************
//View is about to be dismissed, covered or otherwise hidden from view (called each time it disappers)
//Occurs before other view's viewWillAppear
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[InputStream close];
[OutputStream close];
[InputStream release];
InputStream = nil;
[OutputStream release];
OutputStream = nil;
if (OutputData != nil)
{
[OutputData release];
OutputData = nil;
}
}