Socket Communication instance (objective-C)

Source: Internet
Author: User

In objective-C, the cocatouch framework further encapsulates the native socket, that is, stream.

Add cfnetwork framework

Initialize socket

 
Cfreadstreamref readstream; cfwritestreamref writestream; cfstreamcreatepairwithsockettohost (null, (cfstringref) @ "127.0.0.1", 7777, & readstream, & writestream); inputstream = (nsinputstream *) readstream; outputstream = (nsoutputstream *) writestream; [inputstream setdelegate: Self]; [outputstream setdelegate: Self]; [inputstream failed: [nsunloop currentrunloop] formode: Unknown]; [outputstream failed: [nsunloop currentrunloop] formode: nsdefaultrunloopmode]; [inputstream open]; [outputstream open];

Message Processing

-(Void) stream :( nsstream *) thestream handleevent :( nsstreamevent) streamevent {nslog (@ "stream event % I", streamevent); nslog (@ "% @", thestream ); switch (streamevent) {Case nsstreameventopencompleted: nslog (@ "stream opened"); break; Case nsstreameventhasbytesavailable: If (thestream = inputstream) {uint8_t buffer [1024]; int Len; while ([inputstream hasbytesavailable]) {Len = [inputstream read: Buffer maxleng TH: sizeof (buffer)]; If (LEN> 0) {nsstring * output = [[nsstring alloc] initwithbytes: Buffer length: Len encoding: nsasciistringencoding]; If (nil! = Output) {nslog (@ "server said: % @", output); [self messagereceived: output] ;}}} break; Case nsstreameventerroccurred: nslog (@ "can not connect to the host! "); Break; case when: [thestream close]; [thestream removefromrunloop: [nsunloop currentrunloop] formode: nsdefaultrunloopmode]; [thestream release]; thestream = nil; break; default: nslog (@ "unknown event ");}}

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.