IOS socket-based C/S network communication architecture (next)

Source: Internet
Author: User

previously implemented a simple Server program, the service side passed void Writestreamclientcallback (Cfwritestreamref stream, Cfstreameventtype Eventt ype, void* clientcallbackinfo) function sends "Hello" to the client. client! "If the client receives a successful message, it will show" Hello. " client!

”。 You need to display the message sent by the server. Then it is necessary to define a Uilabel output (Iboutlet) to display the message; The client also needs to add two button, an action event method to receive the service-side message Receivedata: and send the Client "received, the server" The action event method of the message senddata:; Join the association is able, relatively simple, to take a look at the detailed 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       //Set the ports to 8734. Ability to change @interface viewcontroller:uiviewcontroller<nsstreamdelegate>{int flag According to details    ,//operation flag 0 for Send 1 for receive}@ Property (Nonatomic, retain) Nsinputstream *inputstream; @property (nonatomic, retain) Nsoutputstream *outputstream;@ Property (weak, nonatomic) Iboutlet UILabel *message;    The client displays messages from the server-(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 is the need to fill in the IP address, according to their own routing can use the IP to decide, here is 192.168.1.103, assuming not know to be able to download the 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 event method from client-(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 to 2048 bytes, this size will have a very large effect 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 is capable of receiving data writes, using 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 data to the server//must close the output stream otherwise, the server side will never stop reading.            [Self.outputstream Close];        } break;            Case nsstreameventerroroccurred://Data stream error occurred 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
from the code to know. The client uses APPLE's own nsstream to achieve the simple basic data flow operation.

if there are any incorrect places, please point out!



Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

IOS socket-based C/S network communication architecture (next)

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.