iOS Network programming Practice--nsstream Implementation TCP Socket iphone client

Source: Internet
Author: User

Client we use the iphone app, the screen is relatively simple. Click the Send button to send some strings to the server past. Clicking the Receive button reads some strings from the server and displays them on the screen.

The UI portion of the client app is no longer covered, we look directly at the Code section, the socket client can be implemented with Cfstream or nsstream, Cfstream implementation is the same as the server side. In order to introduce more knowledge to the reader, we use Nsstream to realize this example. Nsstream implementations use the Objective-c language, some object-oriented classes.

Let's look at the client view Controller ViewController.h

#import <CoreFoundation/CoreFoundation.h> #include <sys/socket.h> #include <netinet/in.h> #define PORT 9000 @interface viewcontroller:uiviewcontroller<nsstreamdelegate>{int flag;//operation flag 0 for Send 1 for receive} @property (non Atomic, retain) Nsinputstream *inputstream; @property (nonatomic, retain) Nsoutputstream *outputstream; @property (Weak, nonatomic) Iboutlet UILabel *message; -(Ibaction) SendData: (ID) sender;-(ibaction) Receivedata: (ID) sender; @end

Define properties InputStream and OutputStream, which are input stream nsinputstream and output stream Nsoutputstream class. They correspond to the input stream cfreadstreamref and the output stream cfwritestreamref in the server Cfstream implementation.

The View controller VIEWCONTROLLER.M initializes the network method initnetworkcommunication code:

-(void) Initnetworkcommunication{cfreadstreamref readstream; Cfwritestreamref Writestream; Cfstreamcreatepairwithsockettohost (NULL, (cfstringref) @ "192.168.1.103″, PORT, &readstream, &writestream);   ①_inputstream = (__bridge_transfer nsinputstream *) Readstream; ②_outputstream = (__bridge_transfer nsoutputstream*) Writestream;  ③[_inputstream setdelegate:self];  ④[_outputstream setdelegate:self];  ⑤[_inputstream Scheduleinrunloop:[nsrunloop Currentrunloop]formode:nsdefaultrunloopmode]; ⑥[_outputstream Scheduleinrunloop:[nsrunloop Currentrunloop]formode:nsdefaultrunloopmode];  ⑦[_inputstream Open];  ⑧[_outputstream Open];  ⑨}

Click the Send and Receive button to trigger the following method:

/* Click the Send button  */-(ibaction) SendData: (ID) Sender {flag = 0;[ Self initnetworkcommunication];} /* Click the Receive button  */-(ibaction) Receivedata: (ID) Sender {flag = 1;[ Self initnetworkcommunication];}

They all call the Initnetworkcommunication method and set the operation to identify flag, and if flag sends data to 0, flag 1 receives the data.

Changes in the state of the stream trigger many events and callback methods defined in the Nsstreamdelegate protocol stream:handleevent:, its code is as follows:

-(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 (flag ==1 && Thestream = = _inputstream) {Nsmutabledata *input = [[Nsmutabledata alloc] init];uint8_t buffer[102  4];  ①int len;while ([_inputstream hasbytesavailable]) ②{len = [_inputstream read:buffer maxlength:sizeof (buffer)]; ③if (Len > 0) {[input Appendbytes:buffer Length:len];} NSString *resultstring = [[NSString alloc]initwithdata:input encoding:nsutf8stringencoding]; NSLog (@ "Receive:%@", resultstring); _message.text = resultstring;} Break;case nsstreameventhasspaceavailable:event = @ "nsstreameventhasspaceavailable"; if (flag ==0 && TheStream = = _outputstream) {//output UInt8 buff[] = "Hello server!"; ④[_outputstream write:buff Maxlength:strlen ((const CHAr*) buff) +1]; ⑤//closing the output stream [_outputstream close];} Break;case nsstreameventerroroccurred:event = @ "nsstreameventerroroccurred"; [Self close]; ⑥break;case nsstreameventendencountered:event = @ "nsstreameventendencountered"; NSLog (@ "error:%d:%@", [[Thestream Streamerror] Code],[[thestream Streamerror] localizeddescription]); Break;default:  [Self close]; ⑦event = @ "Unknown"; break;} NSLog (@ "event?? %@ ", event);}

In the Read Data branch (nsstreameventhasbytesavailable), the code ① behavior reads the data preparation buffer, which in this case is set to 1024 bytes, this size will have a lot of influence on the reading of the stream. The ② line code uses the Hasbytesavailable method to determine if the stream has data that can be read, and if there is readable data, it is read in a loop. The ③ line code uses the stream's Read:maxlength: method to read the data to the buffer, the 1th parameter is the buffer object, and the 2nd parameter is the byte length of the read buffer.

In the Write Data branch (nsstreameventhasspaceavailable), the code ④ line is the data to be written, the ⑤ line code [_outputstream write:buff Maxlength:strlen ((const char *) buff) +1] is written as data method.

The ⑥ and ⑦ line code [self close] calls the Close method closed, and the Close method code is as follows:

-(void) Close{[_outputstream close];[ _outputstream Removefromrunloop:[nsrunloop Currentrunloop]formode:nsdefaultrunloopmode]; [_outputstream Setdelegate:nil]; [_inputstream Close]; [_inputstream Removefromrunloop:[nsrunloop Currentrunloop]formode:nsdefaultrunloopmode]; [_inputstream Setdelegate:nil];}

iOS Network programming Practice--nsstream Implementation TCP Socket iphone client

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.