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 ");}}