4
Setting Socket Connection Yo u can use the CFStream API to establish a socket connection. The NSStrea m class does not support connecting to a remote host on iOS. CFStream does support this behavior, however, and once you have crea ted your streams with the CFStream API, you can cast your CFStreams to NSStreams. - (void)connection:(NSString*)serviceName forIpAddress:( NSString *)ipAddress forPort:( NSString *)portNo { if (inputStream && outputStream)  [self close]; NSString *urlString = [NSString stringWithFormat :@"http://%@" , ipAddress]; NSURL *website = [NSURL URLWithString:urlString]; if (!website) { NSLog(@"%@ is not a valid URL" , website); } CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFStreamCreatePairWithSocketToHost (NULL, (CFStringRef )[website host], [portNo intValue], &readStream, &writeStream); CFReadStreamSetProperty (readStream, kCFStreamPropertyShouldCloseNativeSocket , kCFBooleanTrue); CFWriteStreamSetProperty (writeStream, kCFStreamPropertyShouldCloseNativeSocket , kCFBooleanTrue); inputStream = (NSInputStream *)readStream; outputStream = (NSOutputStream *)writeStream; [self open]; } - (void)open { [inputStream setDelegate:self ]; [outputStream setDelegate:self ]; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop ] forMode:NSDefaultRunLoopMode ]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop ] forMode:NSDefaultRunLoopMode ]; [inputStream open]; [outputStream open]; } Once you have cast the CFStreams to NSStreams, set the delegate, schedule the stream on a run loop, and open the stream as usual. The delegate should begin to receive stream-event messages (stream:ha ndleEvent:). This method is described below in 'Reading From Socket Connection' section.

Socket Programing for IOS

Embed Size (px)

Citation preview

Page 1: Socket Programing for IOS

7/23/2019 Socket Programing for IOS

http://slidepdf.com/reader/full/socket-programing-for-ios 1/4

Setting Socket Connection

You can use the CFStream API to establish a socket connection. The NSStream class does not

support connecting to a remote host on iOS. CFStream does support this behavior, however, and

once you have created your streams with the CFStream API, you can cast your CFStreams toNSStreams.

- (void)connection:(NSString*)serviceName forIpAddress:(NSString *)ipAddressforPort:(NSString *)portNo

{

if (inputStream && outputStream)

  [self close];

NSString *urlString = [NSString stringWithFormat:@"http://%@", ipAddress];

NSURL *website = [NSURL URLWithString:urlString];

if (!website) {

NSLog(@"%@ is not a valid URL", website);

}

CFReadStreamRef readStream;CFWriteStreamRef writeStream;CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef )[website host], [portNo

intValue], &readStream, &writeStream);

CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket,kCFBooleanTrue);

CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket,

kCFBooleanTrue);

inputStream = (NSInputStream *)readStream;

outputStream = (NSOutputStream *)writeStream;

[self open];}

- (void)open{

[inputStream setDelegate:self ];

[outputStream setDelegate:self ];[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]

forMode:NSDefaultRunLoopMode];

[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]

forMode:NSDefaultRunLoopMode];[inputStream open];

[outputStream open];}

Once you have cast the CFStreams to NSStreams, set the delegate, schedule the stream on a run

loop, and open the stream as usual. The delegate should begin to receive stream-event messages

(stream:handleEvent:). This method is described below in 'Reading From Socket Connection'section.

Page 2: Socket Programing for IOS

7/23/2019 Socket Programing for IOS

http://slidepdf.com/reader/full/socket-programing-for-ios 2/4

Reading From Socket Connection

After a NSInputStream object is sent open, you can find out about its status, whether it has bytes

available to read, and the nature of any error with the following messages:

streamStatus

hasBytesAvailablestreamError

The returned status is an NSStreamStatus constant indicating that the stream is opening, reading,at the end of the stream, and so on. This code for reading data from socket connectionlisted below.

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

NSString *event;

switch (streamEvent)  {

case NSStreamEventNone:event = @"NSStreamEventNone";break;

case NSStreamEventOpenCompleted:

event = @"NSStreamEventOpenCompleted";break;

case NSStreamEventHasBytesAvailable:event = @"NSStreamEventHasBytesAvailable";

if (theStream == inputStream)

{uint8_t buffer[1024];

int len;

while ([inputStream hasBytesAvailable]){

len = [inputStream read:buffer maxLength:1024];

if (len > 0)

{

NSMutableString *output = [[NSMutableString alloc]initWithBytes:buffer length:len encoding:NSUTF8StringEncoding];

NSLog(@"Received data--------------------%@", output);

}

}

}break;

case NSStreamEventHasSpaceAvailable:event = @"NSStreamEventHasSpaceAvailable";

Page 3: Socket Programing for IOS

7/23/2019 Socket Programing for IOS

http://slidepdf.com/reader/full/socket-programing-for-ios 3/4

break;

case NSStreamEventErrorOccurred:event = @"NSStreamEventErrorOccurred";

[self close];

break;

case NSStreamEventEndEncountered:event = @"NSStreamEventEndEncountered";

[self close];

break;

default:event = @"Unknown";break;

}

  NSLog(@"event------%@",event);}

When an NSInputStream object reaches the end of a stream, it sends the delegate aNSStreamEventEndEncountered event in a stream:handleEvent:message. The delegate shoulddispose of the object by doing the mirror-opposite of what it did to prepare the object. Also we

should do When the NSInputStream object experiences errors processing the stream.

- (void)close

{

[inputStream close];[outputStream close];[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop]

forMode:NSDefaultRunLoopMode];

  [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop]forMode:NSDefaultRunLoopMode];  [inputStream setDelegate:nil];

  [outputStream setDelegate:nil];inputStream = nil;outputStream = nil;

}

Writing To Socket Connection

After a NSOutputStream object is sent open, you can find out about its status, whether it hasspace for writing data, and the nature of any error with the following messages:

streamStatus

hasSpaceAvailablestreamError

The returned status is an NSStreamStatus constant indicating that the stream is opening, writing,at the end of the stream, and so on. This code for writing data to socket connection listed below.

Page 4: Socket Programing for IOS

7/23/2019 Socket Programing for IOS

http://slidepdf.com/reader/full/socket-programing-for-ios 4/4

- (void)dataSending:(NSString*)data

{

if (outputStream){

if (![outputStream hasSpaceAvailable])return;

NSData *_data=[data dataUsingEncoding:NSUTF8StringEncoding];int data_len = [_data length];

uint8_t *readBytes = (uint8_t *)[_data bytes];

int byteIndex=0;unsigned int len=0;

while (TRUE)

{

len = ((data_len - byteIndex >= 40960) ?  40960 : (data_len-byteIndex));

if (len==0)

break;

uint8_t buf[len];

(void)memcpy(buf, readBytes, len);len = [outputStream write:(const uint8_t *)buf maxLength:len];

byteIndex += len;

readBytes += len;}

NSLog(@"Sent data----------------------%@",data); 

}}