The standard iPhone recommendation is CFNetwork library programming. Its encapsulated open source library is Cocoa AsyncSocket library, which is used to simplify CFNetwork calls. It provides asynchronous operations with major features: queue non-blocking read and write, and optional timeout. You can call it to read and write, and it will inform you of automatic socket reception when finished. If you call it to receive connections, it will start a new instance for each connection, and of course, you can immediately turn off the connection delegate support. Errors, connections, receives, full reads, full writes, progress, and disconnections can all be called in delegate mode from Run Loop-based rather than threaded ones. Although you can use it in the main thread or worker thread, you don’t need to. It calls the delegate method asynchronously, using NSRunLoop. Delegate methods include socket parameters that allow you to distinguish between self-contained classes in multiple instances. You don’t need to manipulate streams or sockets, this class does all the supporting for IPV4 and IPV6 TCP streams for you

Add: CFNetwork. Framework TCP client #import "asyncsocket. h" @interface HelloiPhoneViewController : UIViewController { UITextField * textField; AsyncSocket * asyncSocket; } @property (retain, nonatomic) IBOutlet UITextField *textField; - (IBAction) buttonPressed: (id)sender; - (IBAction) textFieldDoneEditing: (id)sender; @end connects to the server using connectToHost where the connection is needed where self is required in the initWithDelegate argument. The functions that each Socket responds to in this object pointer will be called by ASyncSocket. InitWithDelegate will pass the current object in, AsyncSocket = [[asyncSocket alloc] initWithDelegate:self]; NSError *err = nil; if(! [asyncSocket connectToHost:host on:port error:&err]) { NSLog(@"Error: %@", err); } NSData objects are used for both SOCKET sending and receiving. It is defined as http://developer.apple.com/library/mac / # documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference. The HTML NSData mainly take a (id) data to data space and length Length. Nsstrings converts NSData object NSData * xmlData = [@ "testdata" dataUsingEncoding: NSUTF8StringEncoding]; NSData is converted to NSString NSData * data; NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; The AsyncSocket writeData method sends data, It has the following definitions: - (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag; Here is an example statement. NSData* aData= [@"test data" dataUsingEncoding: NSUTF8StringEncoding]; [sock writeData:aData withTimeout:-1 tag:1]; The onSocket overload function, like the onSocket override function, is specifically used to handle data sent through the SOCKET:  -(void)onSocket(AsyncSocket *)sock didWriteDataWithTag:(long)tag { NSLog(@"thread(%),onSocket:%p didWriteDataWithTag:%d",[[NSThread currentThread] name], sock,tag); } Receive Socket data. Overloaded functions on onSocket, -(void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag Convert it to NSString in the middle for display. NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"===%@",aStr); [aStr release]; 6, TCP connection read a specified length of data socket connection, may read a fixed length of bytes [socket readDataToLength: withTimeout :tag]Copy the code

– (void) onSocket :(AsyncSocket *) sock willDisconnectWithError :(NSError *)err; Error occurs, socket closed, can call – call back process socket “unreadData” according to the last byte of data, when connected, the delegate during onSocket: didAcceptNewSocket: Or onSocket: didConnectToHost: before the call

- (void) onSocketDidDisconnect:(ASyncSocket *)sock; This method works if you want to release the socket after disconnection when the socket is disconnected due to or without an error, In the onSocket: willDisconnectWithError release is unsafe - (void) onSocket: (AsyncSocket *) the sock didAcceptNewSocket: (AsyncSocket *)newSocket; Called when a socket is generated to handle a connection. This method returns the new socket of the run-loop on the thread and the delegate it should handle. If omitted, [NSRunLoop cunrrentRunLoop] - (BOOL) onSocketWillConnect:(AsyncSocket *)sock; - (void) onSocket:(AsyncSocket *)sock didConnectToHost :(NSString *)host port:(UINt16)port; Called when the socket connection is about to be read or written, the host property is an IP address, Instead of a DNS name - (void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long) tag; Called when the socket has finished reading the required data into memory. If there is an error does not call - (void) onSocket: (Asyncsocket *) the sock didReadPartialDataOfLength: NSUInteger partiaLength tag (long) the tag; Called when a socket is reading data but has not finished reading. If readToData: or readToLength: - (void) onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag; When a socket has completed writing time of the request data calls - (void) onSocket: (AsyncSocket *) the sock didWritePartialDataOfLength: (partialLength NSUInteger) tag:(long)tag; Called when a socket has written some data but has not completed the entire write, It can be used to update the progress bar, etc - NSTimeInterval onSocket: (AsyncSocket *) the sock shouldTimeoutReadWithTag (long) tag Elapsed :(NSTimeInterval) exsed bytesDone (NSUInteger)length called when the read operation has expired and has not yet completed. This method allows optional timeout delay and will be extended at some point if a positive interval is returned. If you do not implement this method, you will return a negative elapsed interval as usual. The Elapsed parameter is the sum of the original elapsed times, plus any additions previously added by this method, and the length parameter is the number of bytes read so far by the read operation. Note that if you return a positive number, This method may be a single read multiple calls - (NSTimeInterval) onSocket: (AsyncSocket *) the sock shouldTimeoutWriteWithTag (long) tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length; If a write operation has reached its timeout but has not completed, as above - (void) onSocketDidSecure:(AsyncSocket *)sock; This method is only called if you use the startTLS method. If SSL/TLS is an invalid certificate, the socket is immediately closed. OnSocket: willDisconnectWithError: proxy method should call with specific SSL error code - (BOOL) canSafelySetDelegate used to view before change it, with the current business entrust a pending (read/write). Once one of the receive or connect methods is called, the AsyncSocket instance is locked, and the other receive/connect methods are not called without first disconnecting the socket. If the attempt fails or times out, Either of these methods return NO or call onSocket: willDisconnectWithError: or onSockedDidDisconnect when incoming connection is accepted, AsyncSocket call commissioned by multiple methods. These methods according to chronological order: 1. The onSocket: didAcceptNewSocket: 2. OnSocket: wantsRunLoopForNewSocket: 3. OnSocketWillConnect: Your server code will need to keep accepted socket (if you want to accept it), is the best place to do this may be in onSocket: didAcceptNewSocket: method of reading and writing flow has been accepted by the new socket set, OnSocket: didConnectToHost: port method will at the appropriate operating cycle call multi-threaded note, if you want to by implementing onSocket: wantsRunLoopForNewSocket: To move another newly accepted socket to another looped socket. Then, should be before the call to read and write or startTLS method, wait until the onSocket: didConnectToHost: port: method. - (BOOL) acceptOnPort:(UInit16)port error:(NSError **)errPtr; Tell the socket to start listening and accepting connections on the specified port. When a connection arrives, AsyncSocket instances will call various delegate methods, Socket will listen to all available interfaces (wifi, Ethernet etc.) - (BOOL) connectToHost:(NSString *)hostname onPort:(UInt16)port error :(NSError **)errPtr; - (BOOL) connectToAddress (NSData *)remoteAddr Error (NSError *)errPtr; - (BOOL) connectToAddress (NSData *)remoteAddr Error (NSError *)errPtr; For example, the NSData object is returned from the address method of NSNetService. If there is an existing SockADDR structure, it can be converted to an NSData object, like this:Copy the code

struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len]; struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];

- (void) disconnect; If the socket has not been disconnected, the onSocketDidDisconnect delegate method will be called immediately before the method returns. Note the recommended way to release AsyncSocket instances:  [asyncSocket setDelegate:nil]; [asyncSocket disconnect]; [asyncSocket release]; - (void) disconnectAfterReading; Disconnect when all pending reads have been completed. After the call, the read and write methods are useless and the socket will be disconnected even if there is still writing to be done - (NSString *)connectedHost; - (UInt16)connectedPort; - (NSString *)localHost; - (UInt16)localPort; Return local and remote hosts and ports to the connected socket, If no connection returns nil or 0, the host will be an IP address - (NSData *) connectedAddress - (NSData *) localAddresss Returns the local and remote addresses to the connected socket, Specify a package in a NSData object readData socketaddr structure and writeData method will not be a block (asynchronous) are they when read complete onSocket: didReadData: withTag: When the delegate invocation When writing complete onSocket: didWriteDataWithTag: delegate calls may choose any of the read/write operation timeout (in order not to timeout, use a negative time interval. If the read/write operation timeout, corresponding onSocket: shouldTimeout... The delegate is invoked to selectively allow us to extend the timeout After a timeout, onSocket: willDisconnectWithError: Method is called, onSocketDidDisconnect Tag just for convenience, You can use it as an array index, step number, state id, pointer, etc. - (void) readDataWithTimeout:(NSTimeInterval)tiemout tag:(long)tag; Read bytes available on the socket for the first time. If timeout is negative, Read operations will not use timeout - (void) readDataWithTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInterger)offset tag:(long)tag; The first byte that becomes available on the socket is appended to the given byte buffer, starting at the given offset. If necessary, the given buffer size is automatically increased. If timeout is negative, the read operation will not use timeout. The socket will create a buffer for us and if bufferOffset is greater than the given buffer length, the method will be useless, the delegate will not be called and if you pass a buffer, you can't change it in any way while AsyncSocket is using it and then it's done, OnSocket: didReadData: withTag returned data is a subset of the given buffer That is to say, It will be referenced to the bytes of the given buffer to be appended - (void) readDataToLength:(NSUInterger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag; Read the given number of bytes, if length is 0, the method is useless, The delegate will not be called - (void) readDataToLength (NSUInteger) Length withTimeout (NSTimeInterval)tiemout Buffer (NSMutableData *)buffer bufferOffset:(NSUInteger) offset tag:(long)tag; Read a given number of bytes, start at a given offset, Bytes will be appended to the given byte buffer - (void) readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag; Read bytes up to (including) the "data" parameter passed as delimiter if 0 or length of data is passed, the "data" parameter, this method is useless, the delegate will not be called to read a row from the socket, use the "data" parameter as the row delimiter (as in HTTP CRLF) note, This method is not a character set, so if a separator is present, it can naturally be used as part of the encoding, ReadDataToData :(NSData *)data withTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger) offset tag:(long)tag; Read bytes until (including) the "data" parameter passed as delimited, starting at the given offset, the bytes will be appended to the given byte buffer. Read a line from the socket, - (void) writeData:(NSData *)data withTimeout:(NSTimeInterval) timeout tag:(long)tag; Write data to the socket, When complete entrust is called - (float) progressOfReadReturningTag: (long *) tag bytesDone: (NSUInteger *) done total (total NSUInteger *); - (float)progressOfWriteReturningTag:(long *)tag bytesDone:(NSUInteger *)done total:(NSUInteger *)total; Returns the current read/write progress, from 0.0 to 1.0, or Nan if no read/write is in progress (use isNan to check)Copy the code

Tag, done, and total will be filled if they are not empty

- (void)startTLS:(NSDictionary *)tlsSettings; Ensure that this method can be called at any time using SSL/TLS connections, and the TLS handshake will take place after all pending reads/writes are complete. This follows a protocol option to send starTTLs-dependent messages at the same time as the queued upgrade to TLS, without having to wait for the write to complete. After this method is called, any read/write planning will take place on the secure link for possible keys and the values set to TLS are documented. Some possible keys are: * - kCFStreamSSLLevel * - kCFStreamSSLAllowsExpiredCertificates * - kCFStreamSSLAllowsExpiredRoots * - kCFStreamSSLAllowsAnyRoot * - kCFStreamSSLValidatesCertificateChain * - kCFStreamSSLPeerName * - KCFStreamSSLCertificates * -kcfStreamSSLisServer If you pass an empty or empty dictionary, the default dictionary will be used. The default Settings will be checked to ensure that certificates are signed by trusted third party certificate authorities and have no expired remote connections. However, It doesn't validate the name on the certificate, unless you give it a name, and that's verified by the kCFStreamSSLPeerName key and the security implications are important to understand imagine that you're trying to create a secure connection to MySecureServer.com, but because of a DNS server that's been attacked, So your socket is directed to MaliciousServer.com and if you just use the default Settings, MaliciousServer.com has a valid certificate and the default Settings will not detect any problems because the certificate is valid in this particular case, to properly protect your connection, The kCFStreamSSLPeerName property should be set to MySecureServer.com. If you do not know the name of the peer's remote host beforehand (for example, you are not sure it is domain.com" or "www.domain.com"), then you can use the default Settings to verify the certificate, This is then verified after a certified distribution using the X509Certificate class, which is part of the CocoaAsyncSocket open source project - (void) enablePrebuffering For processing readDataToData requests, the data must be read out of the socket in small increments. Performance is greatly improved by allowing AsyncSocket to read large chunks of data at once and store any small internal buffer overflows. This is called prebuffering, As if some data can be read before you even ask for it, if you use readDataToData a lot, using prebuffering gives better performance, especially on the iPhone where the default prebuffering state is controlled by the DEFAULT_PREBUFFERING definition, - (BOOL) moveToRunLoop (NSRunLoop *)runLoop; - (BOOL) moveToRunLoop (NSRunLoop *)runLoop; When you create an AsyncSocket, it is added to the current thread runloop. For manually created sockets on threads you intend to use it on, it is easiest to simply create sockets on threads when a new socket is accepted, The delegate onSocket: wantsRunLoopForNewSocket is called allows you to socket is placed on a separate thread, the best combination in the same thread pool design work If, however, on a separate thread, in later time, you need to move a socket, This method must be called from the socket of the currently running thread /runloop. Note: After this method is called, all further methods should call this object from the given runloop. In addition, all delegate calls will be sent to the given runloop - (BOOL)setRunLoopModes:(NSArray *)runLoopModes; - (BOOL)addRunLoopMode:(NSString *)runLoopMode; - (BOOL)removeRunLoopMode:(NSString *)runLoopMode; NSRunLoopCommonModes Allows you to configure the running loop modes used by the socket. The default is NSRunLoopCommonModes. If you want your socket to continue operating in other modes, You may need to add the pattern NSModalPanelRunLoopMode NSEventTrackingRunLoopMode or you may want to use NSRunLoopCommonModes acceptable socket will automatically Inheriting the same runtime loop pattern is like listening on sockets note: NSRunLoopCommonModes are defined in 10.5. For earlier versions, kCFRunLoopCommonModes - (NSArray *) runLoopModes return AsyncSocket instances of the currently running loop mode. The default setting for run loop modes is NSDefaultRunLoopMode - (NSData *) unreadData; An error event in onSocket: willDisconnectWithError: will be called to read any data on the socket + (NSData *) CRLFData; // 0x0D0ACopy the code

– (void) onSocket :(AsyncSocket *) sock willDisconnectWithError :(NSError *)err; Error occurs, socket closed, can call – call back process socket “unreadData” according to the last byte of data, when connected, the delegate during onSocket: didAcceptNewSocket: Or onSocket: didConnectToHost: before the call

- (void) onSocketDidDisconnect:(ASyncSocket *)sock; This method works if you want to release the socket after disconnection when the socket is disconnected due to or without an error, In the onSocket: willDisconnectWithError release is unsafe - (void) onSocket: (AsyncSocket *) the sock didAcceptNewSocket: (AsyncSocket *)newSocket; Called when a socket is generated to handle a connection. This method returns the new socket of the run-loop on the thread and the delegate it should handle. If omitted, [NSRunLoop cunrrentRunLoop] - (BOOL) onSocketWillConnect:(AsyncSocket *)sock; - (void) onSocket:(AsyncSocket *)sock didConnectToHost :(NSString *)host port:(UINt16)port; Called when the socket connection is about to be read or written, the host property is an IP address, Instead of a DNS name - (void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long) tag; Called when the socket has finished reading the required data into memory. If there is an error does not call - (void) onSocket: (Asyncsocket *) the sock didReadPartialDataOfLength: NSUInteger partiaLength tag (long) the tag; Called when a socket is reading data but has not finished reading. If readToData: or readToLength: - (void) onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag; When a socket has completed writing time of the request data calls - (void) onSocket: (AsyncSocket *) the sock didWritePartialDataOfLength: (partialLength NSUInteger) tag:(long)tag; Called when a socket has written some data but has not completed the entire write, It can be used to update the progress bar, etc - NSTimeInterval onSocket: (AsyncSocket *) the sock shouldTimeoutReadWithTag (long) tag Elapsed :(NSTimeInterval) exsed bytesDone (NSUInteger)length called when the read operation has expired and has not yet completed. This method allows optional timeout delay and will be extended at some point if a positive interval is returned. If you do not implement this method, you will return a negative elapsed interval as usual. The Elapsed parameter is the sum of the original elapsed times, plus any additions previously added by this method, and the length parameter is the number of bytes read so far by the read operation. Note that if you return a positive number, This method may be a single read multiple calls - (NSTimeInterval) onSocket: (AsyncSocket *) the sock shouldTimeoutWriteWithTag (long) tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length; If a write operation has reached its timeout but has not completed, as above - (void) onSocketDidSecure:(AsyncSocket *)sock; This method is only called if you use the startTLS method. If SSL/TLS is an invalid certificate, the socket is immediately closed. OnSocket: willDisconnectWithError: proxy method should call with specific SSL error code - (BOOL) canSafelySetDelegate used to view before change it, with the current business entrust a pending (read/write). Once one of the receive or connect methods is called, the AsyncSocket instance is locked, and the other receive/connect methods are not called without first disconnecting the socket. If the attempt fails or times out, Either of these methods return NO or call onSocket: willDisconnectWithError: or onSockedDidDisconnect when incoming connection is accepted, AsyncSocket call commissioned by multiple methods. These methods according to chronological order: 1. The onSocket: didAcceptNewSocket: 2. OnSocket: wantsRunLoopForNewSocket: 3. OnSocketWillConnect: Your server code will need to keep accepted socket (if you want to accept it), is the best place to do this may be in onSocket: didAcceptNewSocket: method of reading and writing flow has been accepted by the new socket set, OnSocket: didConnectToHost: port method will at the appropriate operating cycle call multi-threaded note, if you want to by implementing onSocket: wantsRunLoopForNewSocket: To move another newly accepted socket to another looped socket. Then, should be before the call to read and write or startTLS method, wait until the onSocket: didConnectToHost: port: method. - (BOOL) acceptOnPort:(UInit16)port error:(NSError **)errPtr; Tell the socket to start listening and accepting connections on the specified port. When a connection arrives, AsyncSocket instances will call various delegate methods, Socket will listen to all available interfaces (wifi, Ethernet etc.) - (BOOL) connectToHost:(NSString *)hostname onPort:(UInt16)port error :(NSError **)errPtr; - (BOOL) connectToAddress (NSData *)remoteAddr Error (NSError *)errPtr; - (BOOL) connectToAddress (NSData *)remoteAddr Error (NSError *)errPtr; For example, the NSData object is returned from the address method of NSNetService. If there is an existing SockADDR structure, it can be converted to an NSData object, like this:Copy the code

struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len]; struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];

- (void) disconnect; If the socket has not been disconnected, the onSocketDidDisconnect delegate method will be called immediately before the method returns. Note the recommended way to release AsyncSocket instances:  [asyncSocket setDelegate:nil]; [asyncSocket disconnect]; [asyncSocket release]; - (void) disconnectAfterReading; Disconnect when all pending reads have been completed. After the call, the read and write methods are useless and the socket will be disconnected even if there is still writing to be done - (NSString *)connectedHost; - (UInt16)connectedPort; - (NSString *)localHost; - (UInt16)localPort; Return local and remote hosts and ports to the connected socket, If no connection returns nil or 0, the host will be an IP address - (NSData *) connectedAddress - (NSData *) localAddresss Returns the local and remote addresses to the connected socket, Specify a package in a NSData object readData socketaddr structure and writeData method will not be a block (asynchronous) are they when read complete onSocket: didReadData: withTag: When the delegate invocation When writing complete onSocket: didWriteDataWithTag: delegate calls may choose any of the read/write operation timeout (in order not to timeout, use a negative time interval. If the read/write operation timeout, corresponding onSocket: shouldTimeout... The delegate is invoked to selectively allow us to extend the timeout After a timeout, onSocket: willDisconnectWithError: Method is called, onSocketDidDisconnect Tag just for convenience, You can use it as an array index, step number, state id, pointer, etc. - (void) readDataWithTimeout:(NSTimeInterval)tiemout tag:(long)tag; Read bytes available on the socket for the first time. If timeout is negative, Read operations will not use timeout - (void) readDataWithTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInterger)offset tag:(long)tag; The first byte that becomes available on the socket is appended to the given byte buffer, starting at the given offset. If necessary, the given buffer size is automatically increased. If timeout is negative, the read operation will not use timeout. The socket will create a buffer for us and if bufferOffset is greater than the given buffer length, the method will be useless, the delegate will not be called and if you pass a buffer, you can't change it in any way while AsyncSocket is using it and then it's done, OnSocket: didReadData: withTag returned data is a subset of the given buffer That is to say, It will be referenced to the bytes of the given buffer to be appended - (void) readDataToLength:(NSUInterger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag; Read the given number of bytes, if length is 0, the method is useless, The delegate will not be called - (void) readDataToLength (NSUInteger) Length withTimeout (NSTimeInterval)tiemout Buffer (NSMutableData *)buffer bufferOffset:(NSUInteger) offset tag:(long)tag; Read a given number of bytes, start at a given offset, Bytes will be appended to the given byte buffer - (void) readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag; Read bytes up to (including) the "data" parameter passed as delimiter if 0 or length of data is passed, the "data" parameter, this method is useless, the delegate will not be called to read a row from the socket, use the "data" parameter as the row delimiter (as in HTTP CRLF) note, This method is not a character set, so if a separator is present, it can naturally be used as part of the encoding, ReadDataToData :(NSData *)data withTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger) offset tag:(long)tag; Read bytes until (including) the "data" parameter passed as delimited, starting at the given offset, the bytes will be appended to the given byte buffer. Read a line from the socket, - (void) writeData:(NSData *)data withTimeout:(NSTimeInterval) timeout tag:(long)tag; Write data to the socket, When complete entrust is called - (float) progressOfReadReturningTag: (long *) tag bytesDone: (NSUInteger *) done total (total NSUInteger *); - (float)progressOfWriteReturningTag:(long *)tag bytesDone:(NSUInteger *)done total:(NSUInteger *)total; Returns the current read/write progress, from 0.0 to 1.0, or Nan if no read/write is in progress (use isNan to check)Copy the code

Tag, done, and total will be filled if they are not empty

- (void)startTLS:(NSDictionary *)tlsSettings; Ensure that this method can be called at any time using SSL/TLS connections, and the TLS handshake will take place after all pending reads/writes are complete. This follows a protocol option to send starTTLs-dependent messages at the same time as the queued upgrade to TLS, without having to wait for the write to complete. After this method is called, any read/write planning will take place on the secure link for possible keys and the values set to TLS are documented. Some possible keys are: * - kCFStreamSSLLevel * - kCFStreamSSLAllowsExpiredCertificates * - kCFStreamSSLAllowsExpiredRoots * - kCFStreamSSLAllowsAnyRoot * - kCFStreamSSLValidatesCertificateChain * - kCFStreamSSLPeerName * - KCFStreamSSLCertificates * -kcfStreamSSLisServer If you pass an empty or empty dictionary, the default dictionary will be used. The default Settings will be checked to ensure that certificates are signed by trusted third party certificate authorities and have no expired remote connections. However, It doesn't validate the name on the certificate, unless you give it a name, and that's verified by the kCFStreamSSLPeerName key and the security implications are important to understand imagine that you're trying to create a secure connection to MySecureServer.com, but because of a DNS server that's been attacked, So your socket is directed to MaliciousServer.com and if you just use the default Settings, MaliciousServer.com has a valid certificate and the default Settings will not detect any problems because the certificate is valid in this particular case, to properly protect your connection, The kCFStreamSSLPeerName property should be set to MySecureServer.com. If you do not know the name of the peer's remote host beforehand (for example, you are not sure it is domain.com" or "www.domain.com"), then you can use the default Settings to verify the certificate, This is then verified after a certified distribution using the X509Certificate class, which is part of the CocoaAsyncSocket open source project - (void) enablePrebuffering For processing readDataToData requests, the data must be read out of the socket in small increments. Performance is greatly improved by allowing AsyncSocket to read large chunks of data at once and store any small internal buffer overflows. This is called prebuffering, As if some data can be read before you even ask for it, if you use readDataToData a lot, using prebuffering gives better performance, especially on the iPhone where the default prebuffering state is controlled by the DEFAULT_PREBUFFERING definition, - (BOOL) moveToRunLoop (NSRunLoop *)runLoop; - (BOOL) moveToRunLoop (NSRunLoop *)runLoop; When you create an AsyncSocket, it is added to the current thread runloop. For manually created sockets on threads you intend to use it on, it is easiest to simply create sockets on threads when a new socket is accepted, The delegate onSocket: wantsRunLoopForNewSocket is called allows you to socket is placed on a separate thread, the best combination in the same thread pool design work If, however, on a separate thread, in later time, you need to move a socket, This method must be called from the socket of the currently running thread /runloop. Note: After this method is called, all further methods should call this object from the given runloop. In addition, all delegate calls will be sent to the given runloop - (BOOL)setRunLoopModes:(NSArray *)runLoopModes; - (BOOL)addRunLoopMode:(NSString *)runLoopMode; - (BOOL)removeRunLoopMode:(NSString *)runLoopMode; NSRunLoopCommonModes Allows you to configure the running loop modes used by the socket. The default is NSRunLoopCommonModes. If you want your socket to continue operating in other modes, You may need to add the pattern NSModalPanelRunLoopMode NSEventTrackingRunLoopMode or you may want to use NSRunLoopCommonModes acceptable socket will automatically Inheriting the same runtime loop pattern is like listening on sockets note: NSRunLoopCommonModes are defined in 10.5. For earlier versions, kCFRunLoopCommonModes - (NSArray *) runLoopModes return AsyncSocket instances of the currently running loop mode. The default setting for run loop modes is NSDefaultRunLoopMode - (NSData *) unreadData; An error event in onSocket: willDisconnectWithError: will be called to read any data on the socket + (NSData *) CRLFData; // 0x0D0ACopy the code

– (void) onSocket :(AsyncSocket *) sock willDisconnectWithError :(NSError *)err; Error occurs, socket closed, can call – call back process socket “unreadData” according to the last byte of data, when connected, the delegate during onSocket: didAcceptNewSocket: Or onSocket: didConnectToHost: before the call

- (void) onSocketDidDisconnect:(ASyncSocket *)sock; This method works if you want to release the socket after disconnection when the socket is disconnected due to or without an error, In the onSocket: willDisconnectWithError release is unsafe - (void) onSocket: (AsyncSocket *) the sock didAcceptNewSocket: (AsyncSocket *)newSocket; Called when a socket is generated to handle a connection. This method returns the new socket of the run-loop on the thread and the delegate it should handle. If omitted, [NSRunLoop cunrrentRunLoop] - (BOOL) onSocketWillConnect:(AsyncSocket *)sock; - (void) onSocket:(AsyncSocket *)sock didConnectToHost :(NSString *)host port:(UINt16)port; Called when the socket connection is about to be read or written, the host property is an IP address, Instead of a DNS name - (void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long) tag; Called when the socket has finished reading the required data into memory. If there is an error does not call - (void) onSocket: (Asyncsocket *) the sock didReadPartialDataOfLength: NSUInteger partiaLength tag (long) the tag; Called when a socket is reading data but has not finished reading. If readToData: or readToLength: - (void) onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag; When a socket has completed writing time of the request data calls - (void) onSocket: (AsyncSocket *) the sock didWritePartialDataOfLength: (partialLength NSUInteger) tag:(long)tag; Called when a socket has written some data but has not completed the entire write, It can be used to update the progress bar, etc - NSTimeInterval onSocket: (AsyncSocket *) the sock shouldTimeoutReadWithTag (long) tag Elapsed :(NSTimeInterval) exsed bytesDone (NSUInteger)length called when the read operation has expired and has not yet completed. This method allows optional timeout delay and will be extended at some point if a positive interval is returned. If you do not implement this method, you will return a negative elapsed interval as usual. The Elapsed parameter is the sum of the original elapsed times, plus any additions previously added by this method, and the length parameter is the number of bytes read so far by the read operation. Note that if you return a positive number, This method may be a single read multiple calls - (NSTimeInterval) onSocket: (AsyncSocket *) the sock shouldTimeoutWriteWithTag (long) tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length; If a write operation has reached its timeout but has not completed, as above - (void) onSocketDidSecure:(AsyncSocket *)sock; This method is only called if you use the startTLS method. If SSL/TLS is an invalid certificate, the socket is immediately closed. OnSocket: willDisconnectWithError: proxy method should call with specific SSL error code - (BOOL) canSafelySetDelegate used to view before change it, with the current business entrust a pending (read/write). Once one of the receive or connect methods is called, the AsyncSocket instance is locked, and the other receive/connect methods are not called without first disconnecting the socket. If the attempt fails or times out, Either of these methods return NO or call onSocket: willDisconnectWithError: or onSockedDidDisconnect when incoming connection is accepted, AsyncSocket call commissioned by multiple methods. These methods according to chronological order: 1. The onSocket: didAcceptNewSocket: 2. OnSocket: wantsRunLoopForNewSocket: 3. OnSocketWillConnect: Your server code will need to keep accepted socket (if you want to accept it), is the best place to do this may be in onSocket: didAcceptNewSocket: method of reading and writing flow has been accepted by the new socket set, OnSocket: didConnectToHost: port method will at the appropriate operating cycle call multi-threaded note, if you want to by implementing onSocket: wantsRunLoopForNewSocket: To move another newly accepted socket to another looped socket. Then, should be before the call to read and write or startTLS method, wait until the onSocket: didConnectToHost: port: method. - (BOOL) acceptOnPort:(UInit16)port error:(NSError **)errPtr; Tell the socket to start listening and accepting connections on the specified port. When a connection arrives, AsyncSocket instances will call various delegate methods, Socket will listen to all available interfaces (wifi, Ethernet etc.) - (BOOL) connectToHost:(NSString *)hostname onPort:(UInt16)port error :(NSError **)errPtr; - (BOOL) connectToAddress (NSData *)remoteAddr Error (NSError *)errPtr; - (BOOL) connectToAddress (NSData *)remoteAddr Error (NSError *)errPtr; For example, the NSData object is returned from the address method of NSNetService. If there is an existing SockADDR structure, it can be converted to an NSData object, like this:Copy the code

struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len]; struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];

- (void) disconnect; If the socket has not been disconnected, the onSocketDidDisconnect delegate method will be called immediately before the method returns. Note the recommended way to release AsyncSocket instances:  [asyncSocket setDelegate:nil]; [asyncSocket disconnect]; [asyncSocket release]; - (void) disconnectAfterReading; Disconnect when all pending reads have been completed. After the call, the read and write methods are useless and the socket will be disconnected even if there is still writing to be done - (NSString *)connectedHost; - (UInt16)connectedPort; - (NSString *)localHost; - (UInt16)localPort; Return local and remote hosts and ports to the connected socket, If no connection returns nil or 0, the host will be an IP address - (NSData *) connectedAddress - (NSData *) localAddresss Returns the local and remote addresses to the connected socket, Specify a package in a NSData object readData socketaddr structure and writeData method will not be a block (asynchronous) are they when read complete onSocket: didReadData: withTag: When the delegate invocation When writing complete onSocket: didWriteDataWithTag: delegate calls may choose any of the read/write operation timeout (in order not to timeout, use a negative time interval. If the read/write operation timeout, corresponding onSocket: shouldTimeout... The delegate is invoked to selectively allow us to extend the timeout After a timeout, onSocket: willDisconnectWithError: Method is called, onSocketDidDisconnect Tag just for convenience, You can use it as an array index, step number, state id, pointer, etc. - (void) readDataWithTimeout:(NSTimeInterval)tiemout tag:(long)tag; Read bytes available on the socket for the first time. If timeout is negative, Read operations will not use timeout - (void) readDataWithTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInterger)offset tag:(long)tag; The first byte that becomes available on the socket is appended to the given byte buffer, starting at the given offset. If necessary, the given buffer size is automatically increased. If timeout is negative, the read operation will not use timeout. The socket will create a buffer for us and if bufferOffset is greater than the given buffer length, the method will be useless, the delegate will not be called and if you pass a buffer, you can't change it in any way while AsyncSocket is using it and then it's done, OnSocket: didReadData: withTag returned data is a subset of the given buffer That is to say, It will be referenced to the bytes of the given buffer to be appended - (void) readDataToLength:(NSUInterger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag; Read the given number of bytes, if length is 0, the method is useless, The delegate will not be called - (void) readDataToLength (NSUInteger) Length withTimeout (NSTimeInterval)tiemout Buffer (NSMutableData *)buffer bufferOffset:(NSUInteger) offset tag:(long)tag; Read a given number of bytes, start at a given offset, Bytes will be appended to the given byte buffer - (void) readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag; Read bytes up to (including) the "data" parameter passed as delimiter if 0 or length of data is passed, the "data" parameter, this method is useless, the delegate will not be called to read a row from the socket, use the "data" parameter as the row delimiter (as in HTTP CRLF) note, This method is not a character set, so if a separator is present, it can naturally be used as part of the encoding, ReadDataToData :(NSData *)data withTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger) offset tag:(long)tag; Read bytes until (including) the "data" parameter passed as delimited, starting at the given offset, the bytes will be appended to the given byte buffer. Read a line from the socket, - (void) writeData:(NSData *)data withTimeout:(NSTimeInterval) timeout tag:(long)tag; Write data to the socket, When complete entrust is called - (float) progressOfReadReturningTag: (long *) tag bytesDone: (NSUInteger *) done total (total NSUInteger *); - (float)progressOfWriteReturningTag:(long *)tag bytesDone:(NSUInteger *)done total:(NSUInteger *)total; Returns the current read/write progress, from 0.0 to 1.0, or Nan if no read/write is in progress (use isNan to check)Copy the code

Tag, done, and total will be filled if they are not empty

- (void)startTLS:(NSDictionary *)tlsSettings; Ensure that this method can be called at any time using SSL/TLS connections, and the TLS handshake will take place after all pending reads/writes are complete. This follows a protocol option to send starTTLs-dependent messages at the same time as the queued upgrade to TLS, without having to wait for the write to complete. After this method is called, any read/write planning will take place on the secure link for possible keys and the values set to TLS are documented. Some possible keys are: * - kCFStreamSSLLevel * - kCFStreamSSLAllowsExpiredCertificates * - kCFStreamSSLAllowsExpiredRoots * - kCFStreamSSLAllowsAnyRoot * - kCFStreamSSLValidatesCertificateChain * - kCFStreamSSLPeerName * - KCFStreamSSLCertificates * -kcfStreamSSLisServer If you pass an empty or empty dictionary, the default dictionary will be used. The default Settings will be checked to ensure that certificates are signed by trusted third party certificate authorities and have no expired remote connections. However, It doesn't validate the name on the certificate, unless you give it a name, and that's verified by the kCFStreamSSLPeerName key and the security implications are important to understand imagine that you're trying to create a secure connection to MySecureServer.com, but because of a DNS server that's been attacked, So your socket is directed to MaliciousServer.com and if you just use the default Settings, MaliciousServer.com has a valid certificate and the default Settings will not detect any problems because the certificate is valid in this particular case, to properly protect your connection, The kCFStreamSSLPeerName property should be set to MySecureServer.com. If you do not know the name of the peer's remote host beforehand (for example, you are not sure it is domain.com" or "www.domain.com"), then you can use the default Settings to verify the certificate, This is then verified after a certified distribution using the X509Certificate class, which is part of the CocoaAsyncSocket open source project - (void) enablePrebuffering For processing readDataToData requests, the data must be read out of the socket in small increments. Performance is greatly improved by allowing AsyncSocket to read large chunks of data at once and store any small internal buffer overflows. This is called prebuffering, As if some data can be read before you even ask for it, if you use readDataToData a lot, using prebuffering gives better performance, especially on the iPhone where the default prebuffering state is controlled by the DEFAULT_PREBUFFERING definition, - (BOOL) moveToRunLoop (NSRunLoop *)runLoop; - (BOOL) moveToRunLoop (NSRunLoop *)runLoop; When you create an AsyncSocket, it is added to the current thread runloop. For manually created sockets on threads you intend to use it on, it is easiest to simply create sockets on threads when a new socket is accepted, The delegate onSocket: wantsRunLoopForNewSocket is called allows you to socket is placed on a separate thread, the best combination in the same thread pool design work If, however, on a separate thread, in later time, you need to move a socket, This method must be called from the socket of the currently running thread /runloop. Note: After this method is called, all further methods should call this object from the given runloop. In addition, all delegate calls will be sent to the given runloop - (BOOL)setRunLoopModes:(NSArray *)runLoopModes; - (BOOL)addRunLoopMode:(NSString *)runLoopMode; - (BOOL)removeRunLoopMode:(NSString *)runLoopMode; NSRunLoopCommonModes Allows you to configure the running loop modes used by the socket. The default is NSRunLoopCommonModes. If you want your socket to continue operating in other modes, You may need to add the pattern NSModalPanelRunLoopMode NSEventTrackingRunLoopMode or you may want to use NSRunLoopCommonModes acceptable socket will automatically Inheriting the same runtime loop pattern is like listening on sockets note: NSRunLoopCommonModes are defined in 10.5. For earlier versions, kCFRunLoopCommonModes - (NSArray *) runLoopModes return AsyncSocket instances of the currently running loop mode. The default setting for run loop modes is NSDefaultRunLoopMode - (NSData *) unreadData; An error event in onSocket: willDisconnectWithError: will be called to read any data on the socket + (NSData *) CRLFData; // 0x0D0ACopy the code

– (void) onSocket :(AsyncSocket *) sock willDisconnectWithError :(NSError *)err; Error occurs, socket closed, can call – call back process socket “unreadData” according to the last byte of data, when connected, the delegate during onSocket: didAcceptNewSocket: Or onSocket: didConnectToHost: before the call

- (void) onSocketDidDisconnect:(ASyncSocket *)sock; This method works if you want to release the socket after disconnection when the socket is disconnected due to or without an error, In the onSocket: willDisconnectWithError release is unsafe - (void) onSocket: (AsyncSocket *) the sock didAcceptNewSocket: (AsyncSocket *)newSocket; Called when a socket is generated to handle a connection. This method returns the new socket of the run-loop on the thread and the delegate it should handle. If omitted, [NSRunLoop cunrrentRunLoop] - (BOOL) onSocketWillConnect:(AsyncSocket *)sock; - (void) onSocket:(AsyncSocket *)sock didConnectToHost :(NSString *)host port:(UINt16)port; Called when the socket connection is about to be read or written, the host property is an IP address, Instead of a DNS name - (void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long) tag; Called when the socket has finished reading the required data into memory. If there is an error does not call - (void) onSocket: (Asyncsocket *) the sock didReadPartialDataOfLength: NSUInteger partiaLength tag (long) the tag; Called when a socket is reading data but has not finished reading. If readToData: or readToLength: - (void) onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag; When a socket has completed writing time of the request data calls - (void) onSocket: (AsyncSocket *) the sock didWritePartialDataOfLength: (partialLength NSUInteger) tag:(long)tag; Called when a socket has written some data but has not completed the entire write, It can be used to update the progress bar, etc - NSTimeInterval onSocket: (AsyncSocket *) the sock shouldTimeoutReadWithTag (long) tag Elapsed :(NSTimeInterval) exsed bytesDone (NSUInteger)length called when the read operation has expired and has not yet completed. This method allows optional timeout delay and will be extended at some point if a positive interval is returned. If you do not implement this method, you will return a negative elapsed interval as usual. The Elapsed parameter is the sum of the original elapsed times, plus any additions previously added by this method, and the length parameter is the number of bytes read so far by the read operation. Note that if you return a positive number, This method may be a single read multiple calls - (NSTimeInterval) onSocket: (AsyncSocket *) the sock shouldTimeoutWriteWithTag (long) tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length; If a write operation has reached its timeout but has not completed, as above - (void) onSocketDidSecure:(AsyncSocket *)sock; This method is only called if you use the startTLS method. If SSL/TLS is an invalid certificate, the socket is immediately closed. OnSocket: willDisconnectWithError: proxy method should call with specific SSL error code - (BOOL) canSafelySetDelegate used to view before change it, with the current business entrust a pending (read/write). Once one of the receive or connect methods is called, the AsyncSocket instance is locked, and the other receive/connect methods are not called without first disconnecting the socket. If the attempt fails or times out, Either of these methods return NO or call onSocket: willDisconnectWithError: or onSockedDidDisconnect when incoming connection is accepted, AsyncSocket call commissioned by multiple methods. These methods according to chronological order: 1. The onSocket: didAcceptNewSocket: 2. OnSocket: wantsRunLoopForNewSocket: 3. OnSocketWillConnect: Your server code will need to keep accepted socket (if you want to accept it), is the best place to do this may be in onSocket: didAcceptNewSocket: method of reading and writing flow has been accepted by the new socket set, OnSocket: didConnectToHost: port method will at the appropriate operating cycle call multi-threaded note, if you want to by implementing onSocket: wantsRunLoopForNewSocket: To move another newly accepted socket to another looped socket. Then, should be before the call to read and write or startTLS method, wait until the onSocket: didConnectToHost: port: method. - (BOOL) acceptOnPort:(UInit16)port error:(NSError **)errPtr; Tell the socket to start listening and accepting connections on the specified port. When a connection arrives, AsyncSocket instances will call various delegate methods, Socket will listen to all available interfaces (wifi, Ethernet etc.) - (BOOL) connectToHost:(NSString *)hostname onPort:(UInt16)port error :(NSError **)errPtr; - (BOOL) connectToAddress (NSData *)remoteAddr Error (NSError *)errPtr; - (BOOL) connectToAddress (NSData *)remoteAddr Error (NSError *)errPtr; For example, the NSData object is returned from the address method of NSNetService. If there is an existing SockADDR structure, it can be converted to an NSData object, like this:Copy the code

struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len]; struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];

- (void) disconnect; If the socket has not been disconnected, the onSocketDidDisconnect delegate method will be called immediately before the method returns. Note the recommended way to release AsyncSocket instances:  [asyncSocket setDelegate:nil]; [asyncSocket disconnect]; [asyncSocket release]; - (void) disconnectAfterReading; Disconnect when all pending reads have been completed. After the call, the read and write methods are useless and the socket will be disconnected even if there is still writing to be done - (NSString *)connectedHost; - (UInt16)connectedPort; - (NSString *)localHost; - (UInt16)localPort; Return local and remote hosts and ports to the connected socket, If no connection returns nil or 0, the host will be an IP address - (NSData *) connectedAddress - (NSData *) localAddresss Returns the local and remote addresses to the connected socket, Specify a package in a NSData object readData socketaddr structure and writeData method will not be a block (asynchronous) are they when read complete onSocket: didReadData: withTag: When the delegate invocation When writing complete onSocket: didWriteDataWithTag: delegate calls may choose any of the read/write operation timeout (in order not to timeout, use a negative time interval. If the read/write operation timeout, corresponding onSocket: shouldTimeout... The delegate is invoked to selectively allow us to extend the timeout After a timeout, onSocket: willDisconnectWithError: Method is called, onSocketDidDisconnect Tag just for convenience, You can use it as an array index, step number, state id, pointer, etc. - (void) readDataWithTimeout:(NSTimeInterval)tiemout tag:(long)tag; Read bytes available on the socket for the first time. If timeout is negative, Read operations will not use timeout - (void) readDataWithTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInterger)offset tag:(long)tag; The first byte that becomes available on the socket is appended to the given byte buffer, starting at the given offset. If necessary, the given buffer size is automatically increased. If timeout is negative, the read operation will not use timeout. The socket will create a buffer for us and if bufferOffset is greater than the given buffer length, the method will be useless, the delegate will not be called and if you pass a buffer, you can't change it in any way while AsyncSocket is using it and then it's done, OnSocket: didReadData: withTag returned data is a subset of the given buffer That is to say, It will be referenced to the bytes of the given buffer to be appended - (void) readDataToLength:(NSUInterger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag; Read the given number of bytes, if length is 0, the method is useless, The delegate will not be called - (void) readDataToLength (NSUInteger) Length withTimeout (NSTimeInterval)tiemout Buffer (NSMutableData *)buffer bufferOffset:(NSUInteger) offset tag:(long)tag; Read a given number of bytes, start at a given offset, Bytes will be appended to the given byte buffer - (void) readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag; Read bytes up to (including) the "data" parameter passed as delimiter if 0 or length of data is passed, the "data" parameter, this method is useless, the delegate will not be called to read a row from the socket, use the "data" parameter as the row delimiter (as in HTTP CRLF) note, This method is not a character set, so if a separator is present, it can naturally be used as part of the encoding, ReadDataToData :(NSData *)data withTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger) offset tag:(long)tag; Read bytes until (including) the "data" parameter passed as delimited, starting at the given offset, the bytes will be appended to the given byte buffer. Read a line from the socket, - (void) writeData:(NSData *)data withTimeout:(NSTimeInterval) timeout tag:(long)tag; Write data to the socket, When complete entrust is called - (float) progressOfReadReturningTag: (long *) tag bytesDone: (NSUInteger *) done total (total NSUInteger *); - (float)progressOfWriteReturningTag:(long *)tag bytesDone:(NSUInteger *)done total:(NSUInteger *)total; Returns the current read/write progress, from 0.0 to 1.0, or Nan if no read/write is in progress (use isNan to check)Copy the code

Tag, done, and total will be filled if they are not empty

- (void)startTLS:(NSDictionary *)tlsSettings; Ensure that this method can be called at any time using SSL/TLS connections, and the TLS handshake will take place after all pending reads/writes are complete. This follows a protocol option to send starTTLs-dependent messages at the same time as the queued upgrade to TLS, without having to wait for the write to complete. After this method is called, any read/write planning will take place on the secure link for possible keys and the values set to TLS are documented. Some possible keys are: * - kCFStreamSSLLevel * - kCFStreamSSLAllowsExpiredCertificates * - kCFStreamSSLAllowsExpiredRoots * - kCFStreamSSLAllowsAnyRoot * - kCFStreamSSLValidatesCertificateChain * - kCFStreamSSLPeerName * - KCFStreamSSLCertificates * -kcfStreamSSLisServer If you pass an empty or empty dictionary, the default dictionary will be used. The default Settings will be checked to ensure that certificates are signed by trusted third party certificate authorities and have no expired remote connections. However, It doesn't validate the name on the certificate, unless you give it a name, and that's verified by the kCFStreamSSLPeerName key and the security implications are important to understand imagine that you're trying to create a secure connection to MySecureServer.com, but because of a DNS server that's been attacked, So your socket is directed to MaliciousServer.com and if you just use the default Settings, MaliciousServer.com has a valid certificate and the default Settings will not detect any problems because the certificate is valid in this particular case, to properly protect your connection, The kCFStreamSSLPeerName property should be set to MySecureServer.com. If you do not know the name of the peer's remote host beforehand (for example, you are not sure it is domain.com" or "www.domain.com"), then you can use the default Settings to verify the certificate, This is then verified after a certified distribution using the X509Certificate class, which is part of the CocoaAsyncSocket open source project - (void) enablePrebuffering For processing readDataToData requests, the data must be read out of the socket in small increments. Performance is greatly improved by allowing AsyncSocket to read large chunks of data at once and store any small internal buffer overflows. This is called prebuffering, As if some data can be read before you even ask for it, if you use readDataToData a lot, using prebuffering gives better performance, especially on the iPhone where the default prebuffering state is controlled by the DEFAULT_PREBUFFERING definition, - (BOOL) moveToRunLoop (NSRunLoop *)runLoop; - (BOOL) moveToRunLoop (NSRunLoop *)runLoop; When you create an AsyncSocket, it is added to the current thread runloop. For manually created sockets on threads you intend to use it on, it is easiest to simply create sockets on threads when a new socket is accepted, The delegate onSocket: wantsRunLoopForNewSocket is called allows you to socket is placed on a separate thread, the best combination in the same thread pool design work If, however, on a separate thread, in later time, you need to move a socket, This method must be called from the socket of the currently running thread /runloop. Note: After this method is called, all further methods should call this object from the given runloop. In addition, all delegate calls will be sent to the given runloop - (BOOL)setRunLoopModes:(NSArray *)runLoopModes; - (BOOL)addRunLoopMode:(NSString *)runLoopMode; - (BOOL)removeRunLoopMode:(NSString *)runLoopMode; NSRunLoopCommonModes Allows you to configure the running loop modes used by the socket. The default is NSRunLoopCommonModes. If you want your socket to continue operating in other modes, You may need to add the pattern NSModalPanelRunLoopMode NSEventTrackingRunLoopMode or you may want to use NSRunLoopCommonModes acceptable socket will automatically Inheriting the same runtime loop pattern is like listening on sockets note: NSRunLoopCommonModes are defined in 10.5. For earlier versions, kCFRunLoopCommonModes - (NSArray *) runLoopModes return AsyncSocket instances of the currently running loop mode. The default setting for run loop modes is NSDefaultRunLoopMode - (NSData *) unreadData; An error event in onSocket: willDisconnectWithError: will be called to read any data on the socket + (NSData *) CRLFData; // 0x0D0ACopy the code

– (void) onSocket :(AsyncSocket *) sock willDisconnectWithError :(NSError *)err; Error occurs, socket closed, can call – call back process socket “unreadData” according to the last byte of data, when connected, the delegate during onSocket: didAcceptNewSocket: Or onSocket: didConnectToHost: before the call

- (void) onSocketDidDisconnect:(ASyncSocket *)sock; This method works if you want to release the socket after disconnection when the socket is disconnected due to or without an error, In the onSocket: willDisconnectWithError release is unsafe - (void) onSocket: (AsyncSocket *) the sock didAcceptNewSocket: (AsyncSocket *)newSocket; Called when a socket is generated to handle a connection. This method returns the new socket of the run-loop on the thread and the delegate it should handle. If omitted, [NSRunLoop cunrrentRunLoop] - (BOOL) onSocketWillConnect:(AsyncSocket *)sock; - (void) onSocket:(AsyncSocket *)sock didConnectToHost :(NSString *)host port:(UINt16)port; Called when the socket connection is about to be read or written, the host property is an IP address, Instead of a DNS name - (void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long) tag; Called when the socket has finished reading the required data into memory. If there is an error does not call - (void) onSocket: (Asyncsocket *) the sock didReadPartialDataOfLength: NSUInteger partiaLength tag (long) the tag; Called when a socket is reading data but has not finished reading. If readToData: or readToLength: - (void) onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag; When a socket has completed writing time of the request data calls - (void) onSocket: (AsyncSocket *) the sock didWritePartialDataOfLength: (partialLength NSUInteger) tag:(long)tag; Called when a socket has written some data but has not completed the entire write, It can be used to update the progress bar, etc - NSTimeInterval onSocket: (AsyncSocket *) the sock shouldTimeoutReadWithTag (long) tag Elapsed :(NSTimeInterval) exsed bytesDone (NSUInteger)length called when the read operation has expired and has not yet completed. This method allows optional timeout delay and will be extended at some point if a positive interval is returned. If you do not implement this method, you will return a negative elapsed interval as usual. The Elapsed parameter is the sum of the original elapsed times, plus any additions previously added by this method, and the length parameter is the number of bytes read so far by the read operation. Note that if you return a positive number, This method may be a single read multiple calls - (NSTimeInterval) onSocket: (AsyncSocket *) the sock shouldTimeoutWriteWithTag (long) tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length; If a write operation has reached its timeout but has not completed, as above - (void) onSocketDidSecure:(AsyncSocket *)sock; This method is only called if you use the startTLS method. If SSL/TLS is an invalid certificate, the socket is immediately closed. OnSocket: willDisconnectWithError: proxy method should call with specific SSL error code - (BOOL) canSafelySetDelegate used to view before change it, with the current business entrust a pending (read/write). Once one of the receive or connect methods is called, the AsyncSocket instance is locked, and the other receive/connect methods are not called without first disconnecting the socket. If the attempt fails or times out, Either of these methods return NO or call onSocket: willDisconnectWithError: or onSockedDidDisconnect when incoming connection is accepted, AsyncSocket call commissioned by multiple methods. These methods according to chronological order: 1. The onSocket: didAcceptNewSocket: 2. OnSocket: wantsRunLoopForNewSocket: 3. OnSocketWillConnect: Your server code will need to keep accepted socket (if you want to accept it), is the best place to do this may be in onSocket: didAcceptNewSocket: method of reading and writing flow has been accepted by the new socket set, OnSocket: didConnectToHost: port method will at the appropriate operating cycle call multi-threaded note, if you want to by implementing onSocket: wantsRunLoopForNewSocket: To move another newly accepted socket to another looped socket. Then, should be before the call to read and write or startTLS method, wait until the onSocket: didConnectToHost: port: method. - (BOOL) acceptOnPort:(UInit16)port error:(NSError **)errPtr; Tell the socket to start listening and accepting connections on the specified port. When a connection arrives, AsyncSocket instances will call various delegate methods, Socket will listen to all available interfaces (wifi, Ethernet etc.) - (BOOL) connectToHost:(NSString *)hostname onPort:(UInt16)port error :(NSError **)errPtr; - (BOOL) connectToAddress (NSData *)remoteAddr Error (NSError *)errPtr; - (BOOL) connectToAddress (NSData *)remoteAddr Error (NSError *)errPtr; For example, the NSData object is returned from the address method of NSNetService. If there is an existing SockADDR structure, it can be converted to an NSData object, like this:Copy the code

struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len]; struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];

- (void) disconnect; If the socket has not been disconnected, the onSocketDidDisconnect delegate method will be called immediately before the method returns. Note the recommended way to release AsyncSocket instances:  [asyncSocket setDelegate:nil]; [asyncSocket disconnect]; [asyncSocket release]; - (void) disconnectAfterReading; Disconnect when all pending reads have been completed. After the call, the read and write methods are useless and the socket will be disconnected even if there is still writing to be done - (NSString *)connectedHost; - (UInt16)connectedPort; - (NSString *)localHost; - (UInt16)localPort; Return local and remote hosts and ports to the connected socket, If no connection returns nil or 0, the host will be an IP address - (NSData *) connectedAddress - (NSData *) localAddresss Returns the local and remote addresses to the connected socket, Specify a package in a NSData object readData socketaddr structure and writeData method will not be a block (asynchronous) are they when read complete onSocket: didReadData: withTag: When the delegate invocation When writing complete onSocket: didWriteDataWithTag: delegate calls may choose any of the read/write operation timeout (in order not to timeout, use a negative time interval. If the read/write operation timeout, corresponding onSocket: shouldTimeout... The delegate is invoked to selectively allow us to extend the timeout After a timeout, onSocket: willDisconnectWithError: Method is called, onSocketDidDisconnect Tag just for convenience, You can use it as an array index, step number, state id, pointer, etc. - (void) readDataWithTimeout:(NSTimeInterval)tiemout tag:(long)tag; Read bytes available on the socket for the first time. If timeout is negative, Read operations will not use timeout - (void) readDataWithTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInterger)offset tag:(long)tag; The first byte that becomes available on the socket is appended to the given byte buffer, starting at the given offset. If necessary, the given buffer size is automatically increased. If timeout is negative, the read operation will not use timeout. The socket will create a buffer for us and if bufferOffset is greater than the given buffer length, the method will be useless, the delegate will not be called and if you pass a buffer, you can't change it in any way while AsyncSocket is using it and then it's done, OnSocket: didReadData: withTag returned data is a subset of the given buffer That is to say, It will be referenced to the bytes of the given buffer to be appended - (void) readDataToLength:(NSUInterger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag; Read the given number of bytes, if length is 0, the method is useless, The delegate will not be called - (void) readDataToLength (NSUInteger) Length withTimeout (NSTimeInterval)tiemout Buffer (NSMutableData *)buffer bufferOffset:(NSUInteger) offset tag:(long)tag; Read a given number of bytes, start at a given offset, Bytes will be appended to the given byte buffer - (void) readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag; Read bytes up to (including) the "data" parameter passed as delimiter if 0 or length of data is passed, the "data" parameter, this method is useless, the delegate will not be called to read a row from the socket, use the "data" parameter as the row delimiter (as in HTTP CRLF) note, This method is not a character set, so if a separator is present, it can naturally be used as part of the encoding, ReadDataToData :(NSData *)data withTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger) offset tag:(long)tag; Read bytes until (including) the "data" parameter passed as delimited, starting at the given offset, the bytes will be appended to the given byte buffer. Read a line from the socket, - (void) writeData:(NSData *)data withTimeout:(NSTimeInterval) timeout tag:(long)tag; Write data to the socket, When complete entrust is called - (float) progressOfReadReturningTag: (long *) tag bytesDone: (NSUInteger *) done total (total NSUInteger *); - (float)progressOfWriteReturningTag:(long *)tag bytesDone:(NSUInteger *)done total:(NSUInteger *)total; Returns the current read/write progress, from 0.0 to 1.0, or Nan if no read/write is in progress (use isNan to check)Copy the code

Tag, done, and total will be filled if they are not empty

- (void)startTLS:(NSDictionary *)tlsSettings; Ensure that this method can be called at any time using SSL/TLS connections, and the TLS handshake will take place after all pending reads/writes are complete. This follows a protocol option to send starTTLs-dependent messages at the same time as the queued upgrade to TLS, without having to wait for the write to complete. After this method is called, any read/write planning will take place on the secure link for possible keys and the values set to TLS are documented. Some possible keys are: * - kCFStreamSSLLevel * - kCFStreamSSLAllowsExpiredCertificates * - kCFStreamSSLAllowsExpiredRoots * - kCFStreamSSLAllowsAnyRoot * - kCFStreamSSLValidatesCertificateChain * - kCFStreamSSLPeerName * - KCFStreamSSLCertificates * -kcfStreamSSLisServer If you pass an empty or empty dictionary, the default dictionary will be used. The default Settings will be checked to ensure that certificates are signed by trusted third party certificate authorities and have no expired remote connections. However, It doesn't validate the name on the certificate, unless you give it a name, and that's verified by the kCFStreamSSLPeerName key and the security implications are important to understand imagine that you're trying to create a secure connection to MySecureServer.com, but because of a DNS server that's been attacked, So your socket is directed to MaliciousServer.com and if you just use the default Settings, MaliciousServer.com has a valid certificate and the default Settings will not detect any problems because the certificate is valid in this particular case, to properly protect your connection, The kCFStreamSSLPeerName property should be set to MySecureServer.com. If you do not know the name of the peer's remote host beforehand (for example, you are not sure it is domain.com" or "www.domain.com"), then you can use the default Settings to verify the certificate, This is then verified after a certified distribution using the X509Certificate class, which is part of the CocoaAsyncSocket open source project - (void) enablePrebuffering For processing readDataToData requests, the data must be read out of the socket in small increments. Performance is greatly improved by allowing AsyncSocket to read large chunks of data at once and store any small internal buffer overflows. This is called prebuffering, As if some data can be read before you even ask for it, if you use readDataToData a lot, using prebuffering gives better performance, especially on the iPhone where the default prebuffering state is controlled by the DEFAULT_PREBUFFERING definition, - (BOOL) moveToRunLoop (NSRunLoop *)runLoop; - (BOOL) moveToRunLoop (NSRunLoop *)runLoop; When you create an AsyncSocket, it is added to the current thread runloop. For manually created sockets on threads you intend to use it on, it is easiest to simply create sockets on threads when a new socket is accepted, The delegate onSocket: wantsRunLoopForNewSocket is called allows you to socket is placed on a separate thread, the best combination in the same thread pool design work If, however, on a separate thread, in later time, you need to move a socket, This method must be called from the socket of the currently running thread /runloop. Note: After this method is called, all further methods should call this object from the given runloop. In addition, all delegate calls will be sent to the given runloop - (BOOL)setRunLoopModes:(NSArray *)runLoopModes; - (BOOL)addRunLoopMode:(NSString *)runLoopMode; - (BOOL)removeRunLoopMode:(NSString *)runLoopMode; NSRunLoopCommonModes Allows you to configure the running loop modes used by the socket. The default is NSRunLoopCommonModes. If you want your socket to continue operating in other modes, You may need to add the pattern NSModalPanelRunLoopMode NSEventTrackingRunLoopMode or you may want to use NSRunLoopCommonModes acceptable socket will automatically Inheriting the same runtime loop pattern is like listening on sockets note: NSRunLoopCommonModes are defined in 10.5. For earlier versions, kCFRunLoopCommonModes - (NSArray *) runLoopModes return AsyncSocket instances of the currently running loop mode. The default setting for run loop modes is NSDefaultRunLoopMode - (NSData *) unreadData; An error event in onSocket: willDisconnectWithError: will be called to read any data on the socket + (NSData *) CRLFData; // 0x0D0ACopy the code

– (void) onSocket :(AsyncSocket *) sock willDisconnectWithError :(NSError *)err; Error occurs, socket closed, can call – call back process socket “unreadData” according to the last byte of data, when connected, the delegate during onSocket: didAcceptNewSocket: Or onSocket: didConnectToHost: Before calling an error occurs, socket closed, can be in the call – call back process socket “unreadData” according to the final data bytes, when connected, the delegate during onSocket: didAcceptNewSocket: Call before or onSocket: didConnectToHost: – (void) onSocketDidDisconnect (ASyncSocket *) sock; This method works if you want to release the socket after disconnection when the socket is disconnected due to or without an error, In the onSocket: willDisconnectWithError release is unsafe – (void) onSocket: (AsyncSocket *) the sock didAcceptNewSocket: (AsyncSocket *)newSocket; This method returns the new socket of the run-loop on the thread and the delegate it should handle. If omitted, NSRunLoop cunrrentRunLoop is called when a socket is generated to handle the connection. This method returns the new socket of the run-loop on the thread and the delegate it should handle. If omitted, [NSRunLoop cunrrentRunLoop] – (BOOL) onSocketWillConnect:(AsyncSocket *)sock; – (void) onSocket:(AsyncSocket *)sock didConnectToHost :(NSString *)host port:(UINt16)port; Called when the socket connection is about to be read or written, the host property is an IP address, Instead of a DNS name – (void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long) tag; Called when the socket has finished reading the required data into memory. If there is an error does not call – (void) onSocket: (Asyncsocket *) the sock didReadPartialDataOfLength: NSUInteger partiaLength tag (long) the tag; Called when a socket is reading data but has not finished reading. If readToData: or readToLength: – (void) onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag; When a socket has completed writing time of the request data calls – (void) onSocket: (AsyncSocket *) the sock didWritePartialDataOfLength: (partialLength NSUInteger) tag:(long)tag; Called when a socket has written some data but has not completed the entire write, It can be used to update the progress bar, etc – NSTimeInterval onSocket: (AsyncSocket *) the sock shouldTimeoutReadWithTag (long) tag Elapsed :(NSTimeInterval) exsed bytesDone (NSUInteger)length called when the read operation has expired and has not yet completed. This method allows optional timeout delay and will be extended at some point if a positive interval is returned. If you do not implement this method, you will return a negative elapsed interval as usual. The Elapsed parameter is the sum of the original elapsed times, plus any additions previously added by this method, and the length parameter is the number of bytes read so far by the read operation. Note that if you return a positive number, This method may be a single read multiple calls – (NSTimeInterval) onSocket: (AsyncSocket *) the sock shouldTimeoutWriteWithTag (long) tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length; If a write operation has reached its timeout but has not completed, as above – (void) onSocketDidSecure:(AsyncSocket *)sock; This method is only called if you use the startTLS method. If SSL/TLS is an invalid certificate, the socket is immediately closed. OnSocket: willDisconnectWithError: proxy method should call with specific SSL error code – (BOOL) canSafelySetDelegate used to view before change it, with the current business entrust a pending (read/write). Once one of the receive or connect methods is called, the AsyncSocket instance is locked, and the other receive/connect methods are not called without first disconnecting the socket. If the attempt fails or times out, Either of these methods return NO or call onSocket: willDisconnectWithError: or onSockedDidDisconnect when incoming connection is accepted, AsyncSocket call commissioned by multiple methods. These methods according to chronological order: 1. The onSocket: didAcceptNewSocket: 2. OnSocket: wantsRunLoopForNewSocket: 3. OnSocketWillConnect:

Your server code will need to keep accepted socket (if you want to accept it), is the best place to do this may be in onSocket: didAcceptNewSocket: method of reading and writing flow has been accepted by the new socket set, OnSocket: didConnectToHost: port method will at the appropriate operating cycle call multi-threaded note, if you want to by implementing onSocket: wantsRunLoopForNewSocket: To move another newly accepted socket to another looped socket. Then, should be before the call to read and write or startTLS method, wait until the onSocket: didConnectToHost: port: method. - (BOOL) acceptOnPort:(UInit16)port error:(NSError **)errPtr; Tell the socket to start listening and accepting connections on the specified port. When a connection arrives, AsyncSocket instances will call various delegate methods, Socket will listen to all available interfaces (wifi, Ethernet etc.) - (BOOL) connectToHost:(NSString *)hostname onPort:(UInt16)port error :(NSError **)errPtr; - (BOOL) connectToAddress (NSData *)remoteAddr Error (NSError *)errPtr; - (BOOL) connectToAddress (NSData *)remoteAddr Error (NSError *)errPtr; For example, the NSData object is returned from the address method of NSNetService. If there is an existing SockADDR structure, it can be converted to an NSData object, like this:Copy the code

struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len]; struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len]; – (void) disconnect; If the socket has not been disconnected, the onSocketDidDisconnect delegate method will be called immediately before the method returns. Note the recommended way to release AsyncSocket instances: [asyncSocket setDelegate:nil]; [asyncSocket disconnect]; [asyncSocket release]; – (void) disconnectAfterReading; Disconnect when all pending reads have been completed. After the call, the read and write methods are useless and the socket will be disconnected even if there is still writing to be done – (NSString *)connectedHost; – (UInt16)connectedPort; – (NSString *)localHost; – (UInt16)localPort; Return local and remote hosts and ports to the connected socket, If no connection returns nil or 0, the host will be an IP address – (NSData *) connectedAddress – (NSData *) localAddresss Returns the local and remote addresses to the connected socket, Specifies a SocketADDR structure wrapped around an NSData object

ReadData and writeData method is not block (asynchronous) are they when read complete onSocket: didReadData: withTag: delegate method is called When writing complete onSocket: didWriteDataWithTag: Delegate method calls that can choose the timeout setting for any read/write operation (in order not to time out, use negative time intervals). If the read/write operation timeout, corresponding onSocket: shouldTimeout... The delegate is invoked to selectively allow us to extend the timeout After a timeout, onSocket: willDisconnectWithError: Method is called, onSocketDidDisconnect Tag just for convenience, You can use it as an array index, step number, state id, pointer, etc. - (void) readDataWithTimeout:(NSTimeInterval)tiemout tag:(long)tag; Read bytes available on the socket for the first time. If timeout is negative, Read operations will not use timeout - (void) readDataWithTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInterger)offset tag:(long)tag; The first byte that becomes available on the socket is appended to the given byte buffer, starting at the given offset. If necessary, the given buffer size is automatically increased. If timeout is negative, the read operation will not use timeout. The socket will create a buffer for us and if bufferOffset is greater than the given buffer length, the method will be useless, the delegate will not be called and if you pass a buffer, you can't change it in any way while AsyncSocket is using it and then it's done, OnSocket: didReadData: withTag returned data is a subset of the given buffer That is to say, It will be referenced to the bytes of the given buffer to be appended - (void) readDataToLength:(NSUInterger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag; Read the given number of bytes, if length is 0, the method is useless, The delegate will not be called - (void) readDataToLength (NSUInteger) Length withTimeout (NSTimeInterval)tiemout Buffer (NSMutableData *)buffer bufferOffset:(NSUInteger) offset tag:(long)tag; Read a given number of bytes, start at a given offset, Bytes will be appended to the given byte buffer - (void) readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag; Read bytes up to (including) the "data" parameter passed as delimiter if 0 or length of data is passed, the "data" parameter, this method is useless, the delegate will not be called to read a row from the socket, use the "data" parameter as the row delimiter (as in HTTP CRLF) note, This method is not a character set, so if a separator is present, it can naturally be used as part of the encoding, ReadDataToData :(NSData *)data withTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger) offset tag:(long)tag; Read bytes until (including) the "data" parameter passed as delimited, starting at the given offset, the bytes will be appended to the given byte buffer. Read a line from the socket, - (void) writeData:(NSData *)data withTimeout:(NSTimeInterval) timeout tag:(long)tag; Write data to the socket, When complete entrust is called - (float) progressOfReadReturningTag: (long *) tag bytesDone: (NSUInteger *) done total (total NSUInteger *); - (float)progressOfWriteReturningTag:(long *)tag bytesDone:(NSUInteger *)done total:(NSUInteger *)total; Returns the current read/write progress, from 0.0 to 1.0, or Nan if no read/write is in progress (use isNan to check)Copy the code

Tag, done, and total will be filled if they are not empty

- (void)startTLS:(NSDictionary *)tlsSettings; Ensure that this method can be called at any time using SSL/TLS connections, and the TLS handshake will take place after all pending reads/writes are complete. This follows a protocol option to send starTTLs-dependent messages at the same time as the queued upgrade to TLS, without having to wait for the write to complete. After this method is called, any read/write planning will take place on the secure link for possible keys and the values set to TLS are documented. Some possible keys are: * - kCFStreamSSLLevel * - kCFStreamSSLAllowsExpiredCertificates * - kCFStreamSSLAllowsExpiredRoots * - kCFStreamSSLAllowsAnyRoot * - kCFStreamSSLValidatesCertificateChain * - kCFStreamSSLPeerName * - KCFStreamSSLCertificates * -kcfStreamSSLisServer If you pass an empty or empty dictionary, the default dictionary will be used. The default Settings will be checked to ensure that certificates are signed by trusted third party certificate authorities and have no expired remote connections. However, It doesn't validate the name on the certificate, unless you give it a name, and that's verified by the kCFStreamSSLPeerName key and the security implications are important to understand imagine that you're trying to create a secure connection to MySecureServer.com, but because of a DNS server that's been attacked, So your socket is directed to MaliciousServer.com and if you just use the default Settings, MaliciousServer.com has a valid certificate and the default Settings will not detect any problems because the certificate is valid in this particular case, to properly protect your connection, The kCFStreamSSLPeerName property should be set to MySecureServer.com. If you do not know the name of the peer's remote host beforehand (for example, you are not sure it is domain.com" or "www.domain.com"), then you can use the default Settings to verify the certificate, This is then verified after a certified distribution using the X509Certificate class, which is part of the CocoaAsyncSocket open source project - (void) enablePrebuffering For processing readDataToData requests, the data must be read out of the socket in small increments. Performance is greatly improved by allowing AsyncSocket to read large chunks of data at once and store any small internal buffer overflows. This is called prebuffering, As if some data can be read before you even ask for it, if you use readDataToData a lot, using prebuffering gives better performance, especially on the iPhone where the default prebuffering state is controlled by the DEFAULT_PREBUFFERING definition, - (BOOL) moveToRunLoop (NSRunLoop *)runLoop; - (BOOL) moveToRunLoop (NSRunLoop *)runLoop; When you create an AsyncSocket, it is added to the current thread runloop. For manually created sockets on threads you intend to use it on, it is easiest to simply create sockets on threads when a new socket is accepted, The delegate onSocket: wantsRunLoopForNewSocket is called allows you to socket is placed on a separate thread, the best combination in the same thread pool design work If, however, on a separate thread, in later time, you need to move a socket, This method must be called from the socket of the currently running thread /runloop. Note: After this method is called, all further methods should call this object from the given runloop. In addition, all delegate calls will be sent to the given runloop - (BOOL)setRunLoopModes:(NSArray *)runLoopModes; - (BOOL)addRunLoopMode:(NSString *)runLoopMode; - (BOOL)removeRunLoopMode:(NSString *)runLoopMode; NSRunLoopCommonModes Allows you to configure the running loop modes used by the socket. The default is NSRunLoopCommonModes. If you want your socket to continue operating in other modes, You may need to add the pattern NSModalPanelRunLoopMode NSEventTrackingRunLoopMode or you may want to use NSRunLoopCommonModes acceptable socket will automatically Inheriting the same runtime loop pattern is like listening on sockets note: NSRunLoopCommonModes are defined in 10.5. For earlier versions, kCFRunLoopCommonModes - (NSArray *) runLoopModes return AsyncSocket instances of the currently running loop mode. The default setting for run loop modes is NSDefaultRunLoopMode - (NSData *) unreadData; An error event in onSocket: willDisconnectWithError: will be called to read any data on the socket + (NSData *) CRLFData; // 0x0D0ACopy the code