IPhone network programming first-time chat program instance Development

Source: Internet
Author: User

IPhone Network ProgrammingInitial ExperienceChat programThis document describes how to implement instance development.Chat programFor more information, see the content first. First, use Xcode to name a common View-based application project named Network.

Use network communication flow

The simplest way to use sockets to communicate over the network is to use the NSStream class, which is an abstract class that represents a stream. You can use it to read and write data, it can be used in memory, files, or networks. With the NSStream class, you can write data to the server or read data from the server.

On Mac OS X, you can use the NSHost and NSStream objects to establish a connection to the server, for example:

 
 
  1. NSInputStream *iStream;  
  2.             NSOutputStream *oStream;  
  3.             uint portNo = 500;  
  4.             NSURL *website = [NSURL URLWithString:urlStr];  
  5.             NSHost *host = [NSHost hostWithName:[website host]];  
  6.             [NSStream getStreamsToHost:host  
  7.                                   port:portNo  
  8.                            inputStream:&iStream  
  9.                           outputStream:&oStream]; 

The NSStream class has a method getStreamsToHost: port: inputStream: outputStream:, which creates an input and output stream to the server, but the problem is that iPhone OS does not support getStreamsToHost: port: inputStream: outputStream: therefore, the above Code cannot run in the iPhone application.

To solve this problem, you can add a category to the existing NSStream class and replace the functions provided by the getStreamsToHost: port: inputStream: outputStream: method. Right-click the Classes in Xcode and add the NSStreamAdditions. m file. In the NSStreamAdditions. h file, add the following code:

 
 
  1. #import  
  2. @interface NSStream (MyAdditions)  
  3. + (void)getStreamsToHostNamed:(NSString *)hostName  
  4.                          port:(NSInteger)port  
  5.                   inputStream:(NSInputStream **)inputStreamPtr  
  6.                  outputStream:(NSOutputStream **)outputStreamPtr;  
  7. @end 

Add the following code to the NSStreamAdditions file:

 
 
  1. #import "NSStreamAdditions.h"  
  2. @implementation NSStream (MyAdditions)  
  3. + (void)getStreamsToHostNamed:(NSString *)hostName  
  4.                           port:(NSInteger)port  
  5.                    inputStream:(NSInputStream **)inputStreamPtr  
  6.                   outputStream:(NSOutputStream **)outputStreamPtr  
  7.  {  
  8.      CFReadStreamRef     readStream;  
  9.      CFWriteStreamRef    writeStream;  
  10.      assert(hostName != nil);  
  11.      assert( (port > 0) && (port < 65536) );  
  12.      assert( (inputStreamPtr != NULL) || (outputStreamPtr != NULL) );  
  13.      readStream = NULL;  
  14.      writeStream = NULL;  
  15.      CFStreamCreatePairWithSocketToHost(  
  16.                                         NULL,  
  17.                                         (CFStringRef) hostName,  
  18.                                         port,  
  19.                                         ((inputStreamPtr  != nil) ? &readStream : NULL),  
  20.                                         ((outputStreamPtr != nil) ? &writeStream : NULL)  
  21.                                         );  
  22.          if (inputStreamPtr != NULL) {  
  23.         *inputStreamPtr  = [NSMakeCollectable(readStream) autorelease];  
  24.      }  
  25.      if (outputStreamPtr != NULL) {  
  26.          *outputStreamPtr = [NSMakeCollectable(writeStream) autorelease];  
  27.      }  
  28.  }  
  29.  @end 

The above Code adds a getStreamsToHostNamed: port: inputStream: outputStream: method to the NSStream class. Now you can use this method in your iPhone application to connect to the server using the TCP protocol.

In the NetworkViewController. m file, insert the following code:

 
 
  1. #import "NetworkViewController.h"  
  2. #import "NSStreamAdditions.h"  
  3. @implementation NetworkViewController  
  4. NSMutableData *data;  
  5. NSInputStream *iStream;  
  6. NSOutputStream *oStream; 

Define connectToServerUsingStream: portNo: Method to connect to the server, and then create input and output stream objects:

 
 
  1. -(void) connectToServerUsingStream:(NSString *)urlStr  
  2.                             portNo: (uint) portNo {  
  3.     if (![urlStr isEqualToString:@""]) {  
  4.         NSURL *website = [NSURL URLWithString:urlStr];  
  5.         if (!website) {  
  6.             NSLog(@"%@ is not a valid URL");  
  7.             return;  
  8.         } else {  
  9.             [NSStream getStreamsToHostNamed:urlStr  
  10.                                        port:portNo  
  11.                                 inputStream:&iStream  
  12.                                outputStream:&oStream];              
  13.             [iStream retain];  
  14.             [oStream retain];  
  15.             [iStream setDelegate:self];  
  16.             [oStream setDelegate:self];  
  17.               
  18.             [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]   forMode:NSDefaultRunLoopMode];  
  19.             [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop]   forMode:NSDefaultRunLoopMode];  
  20.             [oStream open];  
  21.             [iStream open];              
  22.         }  
  23. }      

In a running loop, you can schedule input and output streams to receive events to avoid blocking.

Summary:IPhone Network ProgrammingInitial ExperienceChat programI hope this article will help you with the introduction of instance development!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.