Socket-Based C/S network communication in iOS (lower)

Source: Internet
Author: User

Socket-Based C/S network communication in iOS (lower)

In the previous article, a simple Server program was implemented. The Server sends "Hello, client!" to the client through the void WriteStreamClientCallBack (CFWriteStreamRef stream, CFStreamEventType eventType, void * clientCallBackInfo) function !" If the client receives the message successfully, "Hello, client!" is displayed !"; To display messages sent from the server, you need to define a UILabel output port (IBOutlet) to display messages. The client also needs to add two buttons, receiveData, An Action event method used to receive messages from the server: it is simple to add an association with sendData:;, the Action event Method for sending the "received, server" Message from the client, the specific implementation code is as follows:

ViewController. h

# Import
 
  
# Import
  
   
# Include
   
    
# Include
    
     
# Define PORT 8734 // set the PORT to 8734. You can change @ interface ViewController: UIViewController according to the actual situation.
     
      
{Int flag; // The operation flag 0 indicates sending 1 as receiving} @ property (nonatomic, retain) NSInputStream * inputStream; @ property (nonatomic, retain) NSOutputStream * outputStream; @ property (weak, nonatomic) IBOutlet UILabel * message; // The client displays the message from the server-(IBAction) sendData :( id) sender; // send the client message-(IBAction) receiveData :( id) sender; // receives the message from the server @ end
     
    
   
  
 
ViewController. m

# Import "ViewController. h "@ interface ViewController () @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad];}-(void) didReceiveMemoryWarning {[super didreceivemorywarning];} // initialize the client network connection-(void) initNetworkCommunication {CFReadStreamRef readStream; CFWriteStreamRef writeStream; // enter the IP address here, which is determined based on the IP address available for the route. Here it is 192.168.1.103, if you do not know, you can download the IP scanner CFStreamCreatePairWithSocketToHost (NULL, (CFStringRef) @ "192.168.1.103", PORT, & readStream, & writeStream); self. inputStream = (_ bridge_transfer NSInputStream *) readStream; // converts a CFStream object to an NSStream object self. outputStream = (_ bridge_transfer NSOutputStream *) writeStream; // converts a CFStream object to an NSStream object [self. inputStream setDelegate: self]; [self. outputStream setDelegate: self]; [self. inputStream scheduleInRunLoop: [nsunloop currentRunLoop] fo RMode: NSDefaultRunLoopMode]; // NSStream method scheduleInRunLoop: Set Run Loop [self. outputStream scheduleInRunLoop: [nsunloop currentRunLoop] forMode: NSDefaultRunLoopMode]; [self. inputStream open]; // The NSStream open method to open the data stream object [self. outputStream open];} // close the data stream operation-(void) close {[self. outputStream close]; [self. outputStream removeFromRunLoop: [nsunloop currentRunLoop] forMode: NSDefaultRunLoopMode]; [self. OutputStream setDelegate: nil]; [self. inputStream close]; [self. inputStream removeFromRunLoop: [nsunloop currentRunLoop] forMode: NSDefaultRunLoopMode]; [self. inputStream setDelegate: nil];} // Method for sending data events from the client-(IBAction) sendData :( id) sender {flag = 0; // indicates sending [self innetworkitcommunication];} // Method for receiving data events from the server-(IBAction) receiveData :( id) sender {flag = 1; // indicates receiving [self initNetworkCommunication];}-(void) stre Am :( NSStream *) theStream handleEvent :( NSStreamEvent) streamEvent {NSString * event; switch (streamEvent) {case NSStreamEventNone: // event = @ "NSStreamEventNone"; break; case NSStreamEventOpenCompleted: // stream event = @ "NSStreamEventOpenCompleted"; break; case NSStreamEventHasBytesAvailable: // The stream has data to read, when reading data, use event = @ "NSStreamEventHasBytesAvailable"; if (flag = 1 & theStream = _ inputS Tream) {NSMutableData * input = [[NSMutableData alloc] init]; uint8_t buffer [2048]; // read data preparation buffer. In this example, 2048 bytes are set, this size will significantly affect the reading of the stream int len; while ([self. inputStream hasBytesAvailable]) {len = [self. inputStream read: buffer maxLength: sizeof (buffer)]; // read data to the buffer if (len> 0) {[input appendBytes: buffer length: len];} NSString * resultstring = [[NSString alloc] initWithData: input encoding: NSUTF8StringEnco Ding]; NSLog (@ "receive: % @", resultstring); self. message. text = resultstring;} break; case NSStreamEventHasSpaceAvailable: // This stream can receive data writes. When writing data, use event = @ "NSStreamEventHasSpaceAvailable "; if (flag = 0 & theStream = _ outputStream) {// output UInt8 buff [] = "Yes, server! "; // The message sent to the server [self. outputStream write: buff maxLength: strlen (const char *) buff) + 1]; // Method for writing data to the server // The output stream must be disabled. Otherwise, the server keeps reading data and does not stop. [self. outputStream close];} break; case nsstreameventerroccurred: // data stream error event = @ "NSStreamEventErrorOccurred"; [self close]; break; case NSStreamEventEndEncountered: // data stream end event = @ "NSStreamEventEndEncountered"; NSLog (@ "Error: % d: % @", [[theStream streamError] code], [[theStream streamError] localizedDescription]); break; default: [self close]; event = @ "Unknown"; break ;}}@ end
It can be seen from the code that the client uses APPLE's NSStream for implementation, which is a relatively simple basic data flow operation.

If anything is wrong, please point it out!

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.