Apple socket programming, commonly used is the Cfnetwork library programming, socket programming is an asynchronous process, socket join method, not wait until the connection is completed and then execute the next line of code, if you want to complete a connection before the completion of a socket fully bound, Then it will be easy to get an unexpected result.
Connect a socket server you need to determine two information, one is the domain name or IP address of the socket server, and the other is the port number that the server listens to. When trying a new socket connection, we'd better add a connection event listener first.
Cfnetwork Library Programming, its packaged open source Library is the Cocoa Asyncsocket library, it will return notification when the call to read and write method is complete, and can automatically socket receive and start a new instance for each connection, and simplifies some processes.
The code is as follows:
1 //Client2#import"Asyncsocket"3 @interface helloiphoneviewcontroller:uiviewcontroller{4Uitextfield *TextField;5Asyncsocket *Asyncsocket;6 }7@property (retain,nonatomic) iboutlet Uitextfield *textfiled;8-(ibaction) buttonpressed: (ID) sender;9-(Ibaction) textfileddoneediting: (ID) sender;
Here with port=0 is to let the system automatically randomly find an idle port. Others are based on C-style direct calls to system functions.
Read data from the socket server
For the socket instance, after receiving the NSData event first, then call the following two methods one, such as radbyte () or readint () What, in the event controller determines not to read the past Bytesavailable,socket is an asynchronous process, So we can't just read the data at the Socekt, but wait until the client loads all the data from the server to read the data, and the data will generate an error before the data is available, so we can broadcast to the socket instance via the NSData event, so we know when , you can read the data. Use Connecttohost to join the server where you need to connect, with the following code:
1 asyncsocket=[[Asyncsocket alloc] initwithdelegate:self]; 2 nserror *err=Nil; 3 if (! [Asyncsocket connecttohost on:port error:&err]) {4 NSLog (@ "error:%@", err); 5 }6 NSD
NSData A data space with ID and length two properties
1 // nsstring turn into NSData 2 nsdata *xmldata=[@ "data" datausingencoding:nsutf8stringencoding]; 3 // nsdata conversion into NSString 4 NSData *data; 5 nsstring *result=[[nsstring alloc] initwithdata:data encoding:nsutr8stringencoding];
Sending data via Asyncsocket:writedate
1 -(void) WriteData: (NSData *) data withtimeout: (nstimeinterval) timeout tag: (long) tag ; 2 nsdata *adata=[@ "tes" datausingencoding:nsutr8stringencoding]; 3 [Socke writedata:adata withtimeout-1 tag:1];
Handling the sent data by overloading
1 -(void) Onsocket: (Asyncsocet *) sock Didwritedatawithtag: (long) tag2 {{3 NSLog (@ "thread (%), onsocket%p didwritedatawithtag:%d" ) , [[Nsthread CurrentThread] name], sock,tag); 4 }
Receives the socket data in the Onsocket overloaded function
1 -(void) Onsocket: (Asyncsocet *) sock didreaddata: (NSData *) data withtag: (long ) tag;
When the received data is ASCII encoded, you can reconstruct a string by means of the method.
1 nsstring *astr=[[NSString alloc] Initwithdata:data encoding:nsutr8stringencoding]; 2 NSLog (@ "==%@", aStr); 3 [ASTR release]; 4 TCP connection reads length-setting data 5 6[socket ReaddataToLength:withTimeout:tag]; 7 // ============================================
Parsing of some methods
1 -(void) Onsocket: (Asyncsocket *) sock willdisconnecterror: (Nserror *) Err
An error occurred, the socket closed, you can call "Unreaddata" in the Call-back procedure to obtain the socket's last data byte, when connected, the delegate method in Onsocket:didacceptnewsocket: or Onsocket:didconnecttohost: previously called;
1 -(void) Onsocket: (Asyncsocket *) sock didacceptnewsocket (Asyncsocket *) Didacceptnewsocket;
When the socket is disconnected due to or without errors, if you want to release the socket after disconnecting, this method works, while the Onsocket:willdisconnectwitherror release is unsafe;
1 -(void) Onsocket: (Asyncsocket *) sock didacceptnewsocket (Asyncsocket *) didacceptnewsocket
When a socket is generated to handle a connection call, this method returns a new socket on the thread run-loop and the delegate it should handle.
If omitted, [Nsrunloop Cunrrentrunloop] is used;
1 -(void) Onsocket (Asyncsocket *) sock didwritepartialdataoflength: (Nsuinteger) partiallength Tag: (long) tag;
When a socket writes some data, but has not completed the entire write call, it can be used to update the progress bar and other things;
1 -(nstimeinterval) Onsocket (Asyncsocket *) sock Shouldtimeoutreadwithtag: (long) tag Elapsect ( Nstimeinterval)
2 exapsed bytesdone: (nsuinteger) Length
Called when a read operation has timed out but has not yet completed, this method allows the discretionary delay timeout, if a positive time interval is returned,
The read timeout will have a certain amount of expansion, if this method is not implemented, or will return a negative time interval as usual, the elapsed parameter is the sum of the original timeout, plus any additions previously added by this method, the length parameter is
Reads the number of bytes that have been read so far, and note that this method may be called multiple times by a separate read if the return is positive.
When an incoming connection is accepted, Asyncsocket calls multiple delegate methods, which are by time:
1 , Onsocket:didacceptnewsocket; 2 , Onsocket:wantsrunloopfornewsocket; 3, Onsocketwillconnect
-(BOOL) Acceptonport (UInit16) port error: (Nserror *) errptr;
Tells the socket to start listening and accepting connections on the specified port, and when a connection arrives, the Asyncsocket instance invokes various delegate methods, and the socket listens to all available interfaces (WiFi, Ethernet, etc.)
-(BOOL) connecttohost (NSString *) hostname onPort (UInit16) port error: (Nserror *) errptr;
Connect a given host and port, host hostname can be a domain name or an IP address
-(BOOL) connecttoaddress: (NSData *) remoteaddr Error: (Nserror *) errptr;
Connect to a given address, specify a SOCKADDR structure that wraps a NSData object, for example, NSData object is returned from the Nsnetservice address method, and if there is an existing SOCKADDR structure, you can convert it to a NSData object, Like this:
struct sockaddr sa, nsdata *dsa = [NSData datawithbytes:&remoteaddr Length:remoteAddr.sa_len]; struct sockaddr *sa, NSData *DSA = [NSData datawithbytes:remoteaddr length:remoteaddr->sa_len];
Disconnect immediately, and any unread read or write will be discarded
-(void) disconnect ()
Socket programming for iOS learning notes