Network communication of the socket-based C/s structure in IOS (bottom)

Source: Internet
Author: User

The previous article implemented a simple Server-side program that served the service side via void Writestreamclientcallback (Cfwritestreamref stream, Cfstreameventtype ev Enttype, void* clientcallbackinfo) function sends "Hello, client!" to the client. "The message, if the client receives success, it will show" Hello, client! Need to display the message sent by the server, you need to define a Uilabel output (Iboutlet) to display the message, the client also needs to add two buttons, a service-side message to receive the action event method Receivedata: and the sending client "received, the server" The action event method of the message senddata:; Add an association on it, relatively simple, the following is a look at the implementation of the code:

ViewController.h

#import <UIKit/UIKit.h> #import <CoreFoundation/CoreFoundation.h> #include <sys/socket.h> #include <netinet/in.h> #define PORT 8734       //To set the ports to 8734, you can change the @interface according to the specific situation viewcontroller:uiviewcontroller< nsstreamdelegate>{    int flag;//operation flag 0 for Send 1 for receive} @property (Nonatomic, retain) Nsinputstream *inputstream;@ Property (Nonatomic, retain) Nsoutputstream *outputstream; @property (weak, nonatomic) Iboutlet UILabel *message;    Displays messages from the server on the client-(ibaction) SendData: (ID) sender;      Message sent to client-(ibaction) Receivedata: (ID) sender;   Receive messages from the server @end
Viewcontroller.m

#import "ViewController.h" @interface Viewcontroller () @end @implementation viewcontroller-(void) viewdidload{[super    Viewdidload]; }-(void) didreceivememorywarning{[super didreceivememorywarning];}    Initialize Client network connection-(void) initnetworkcommunication{cfreadstreamref readstream;    Cfwritestreamref Writestream; Here need to fill in the IP address, according to their own routing can be used by the IP, here is 192.168.1.103, if not know can download IP scanner cfstreamcreatepairwithsockettohost (NULL, (        CFSTRINGREF) @ "192.168.1.103", PORT, &readstream, &writestream);  Self.inputstream = (__bridge_transfer nsinputstream *) Readstream;              Convert Cfstream object to Nsstream object Self.outputstream = (__bridge_transfer nsoutputstream *) Writestream;    Convert Cfstream object to Nsstream Object [Self.inputstream setdelegate:self];    [Self.outputstream setdelegate:self];    [Self.inputstream Scheduleinrunloop:[nsrunloop Currentrunloop] formode:nsdefaultrunloopmode]; Nsstream method Scheduleinrunloop: Set the Run Loop [self.OutputStream Scheduleinrunloop:[nsrunloop Currentrunloop] formode:nsdefaultrunloopmode];   [Self.inputstream Open];    The Open method of Nsstream opens the Data flow object [Self.outputstream open];    }//Close Data flow operation-(void) close{[Self.outputstream Close];    [Self.outputstream Removefromrunloop:[nsrunloop Currentrunloop] formode:nsdefaultrunloopmode];    [Self.outputstream Setdelegate:nil];    [Self.inputstream Close];    [Self.inputstream Removefromrunloop:[nsrunloop Currentrunloop] formode:nsdefaultrunloopmode]; [Self.inputstream Setdelegate:nil];}   Send data from client to event Method-(Ibaction) SendData: (ID) Sender {flag = 0;    means send [self initnetworkcommunication];   }//receive data event method from server-(ibaction) Receivedata: (ID) Sender {flag = 1;    means receive [self initnetworkcommunication];    }-(void) stream: (Nsstream *) thestream handleevent: (nsstreamevent) streamevent {nsstring *event;        Switch (streamevent) {case Nsstreameventnone://No event occurred = @ "Nsstreameventnone";    Break            Case nsstreameventopencompleted://successfully open stream event = @ "nsstreameventopencompleted";        Break            Case nsstreameventhasbytesavailable://This stream has data to read, use event = @ "Nsstreameventhasbytesavailable" when reading data; if (flag ==1 && Thestream = = _inputstream) {Nsmutabledata *input = [[Nsmutabledata alloc] Init                ]; uint8_t buffer[2048];                Read the data preparation buffer, which is set in this example is 2048 bytes, this size will have a great influence on the reading of the convection int len; while ([Self.inputstream hasbytesavailable]) {len = [Self.inputstream read:buffer maxlen  gth:sizeof (buffer)]; Read data to Buffer if (Len > 0) {[Input Appendbytes:buffer length                    : Len]; }} nsstring *resultstring = [[NSString alloc] Initwithdata:input encoding:nsutf8stringencod                ING];                NSLog (@ "Receive:%@", resultstring); Self.message.text= resultstring;        } break;            Case nsstreameventhasspaceavailable://This stream can receive write data, use event = @ "Nsstreameventhasspaceavailable" when writing data; if (flag ==0 && Thestream = = _outputstream) {//output UInt8 buff[] = "received, Service side!"       ";   Messages sent to the server [Self.outputstream write:buff maxlength:strlen ((const char*) buff) +1];            Write a data method to the server//must shut down the output stream otherwise, it will never stop reading, [Self.outputstream close];        } break;            Case nsstreameventerroroccurred://Data stream Error event = @ "nsstreameventerroroccurred";            [Self close];        Break            Case nsstreameventendencountered://Data Flow End event = @ "nsstreameventendencountered";            NSLog (@ "error:%d:%@", [[Thestream Streamerror] code], [[Thestream Streamerror] localizeddescription]);        Break            Default: [Self close];            event = @ "Unknown"; BreAk }} @end
As you can see from the code, the client is using APPLE's own Nsstream, which is a relatively simple basic data flow operation.

If there are any wrong places, please point out!

Network communication of the socket-based C/s structure in IOS (bottom)

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.