FMAsyncSocket Class Reference

Inherits from NSObject
Declared in FM.h

– delegate

Use “canSafelySetDelegate” to see if there is any pending business (reads and writes) with the current delegate before changing it. It is, of course, safe to change the delegate before connecting or accepting connections.

- (id)delegate

Discussion

Use “canSafelySetDelegate” to see if there is any pending business (reads and writes) with the current delegate before changing it. It is, of course, safe to change the delegate before connecting or accepting connections.

Declared In

FM.h

– acceptOnPort:error:

Tells the socket to begin listening and accepting connections on the given port. When a connection comes in, the FMAsyncSocket instance will call the various delegate methods (see above). The socket will listen on all available interfaces (e.g. wifi, ethernet, etc)

- (BOOL)acceptOnPort:(UInt16)port error:(NSError **)errPtr

Discussion

Tells the socket to begin listening and accepting connections on the given port. When a connection comes in, the FMAsyncSocket instance will call the various delegate methods (see above). The socket will listen on all available interfaces (e.g. wifi, ethernet, etc)

Declared In

FM.h

– acceptOnInterface:port:error:

This method is the same as acceptOnPort:error: with the additional option of specifying which interface to listen on. So, for example, if you were writing code for a server that has multiple IP addresses, you could specify which address you wanted to listen on. Or you could use it to specify that the socket should only accept connections over ethernet, and not other interfaces such as wifi. You may also use the special strings “localhost” or “loopback” to specify that the socket only accept connections from the local machine.

- (BOOL)acceptOnInterface:(NSString *)interface port:(UInt16)port error:(NSError **)errPtr

Discussion

This method is the same as acceptOnPort:error: with the additional option of specifying which interface to listen on. So, for example, if you were writing code for a server that has multiple IP addresses, you could specify which address you wanted to listen on. Or you could use it to specify that the socket should only accept connections over ethernet, and not other interfaces such as wifi. You may also use the special strings “localhost” or “loopback” to specify that the socket only accept connections from the local machine.

To accept connections on any interface pass nil, or simply use the acceptOnPort:error: method.

Declared In

FM.h

– connectToHost:onPort:error:

Connects to the given host and port. The host may be a domain name (e.g. “deusty.com”) or an IP address string (e.g. “192.168.0.2”)

- (BOOL)connectToHost:(NSString *)hostname onPort:(UInt16)port error:(NSError **)errPtr

Discussion

Connects to the given host and port. The host may be a domain name (e.g. “deusty.com”) or an IP address string (e.g. “192.168.0.2”)

Declared In

FM.h

– connectToHost:onPort:withTimeout:error:

This method is the same as connectToHost:onPort:error: with an additional timeout option. To not time out use a negative time interval, or simply use the connectToHost:onPort:error: method.

- (BOOL)connectToHost:(NSString *)hostname onPort:(UInt16)port withTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr

Discussion

This method is the same as connectToHost:onPort:error: with an additional timeout option. To not time out use a negative time interval, or simply use the connectToHost:onPort:error: method.

Declared In

FM.h

– connectToAddress:error:

Connects to the given address, specified as a sockaddr structure wrapped in a NSData object. For example, a NSData object returned from NSNetService’s addresses method.

- (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr

Discussion

Connects to the given address, specified as a sockaddr structure wrapped in a NSData object. For example, a NSData object returned from NSNetService’s addresses method.

If you have an existing struct sockaddr you can convert it to a NSData object like so: struct sockaddr sa -> NSData dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len]; struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];

Declared In

FM.h

– connectToAddress:withTimeout:error:

This method is the same as connectToAddress:error: with an additional timeout option. To not time out use a negative time interval, or simply use the connectToAddress:error: method.

- (BOOL)connectToAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr

Discussion

This method is the same as connectToAddress:error: with an additional timeout option. To not time out use a negative time interval, or simply use the connectToAddress:error: method.

Declared In

FM.h

– disconnect

Disconnects immediately. Any pending reads or writes are dropped. If the socket is not already disconnected, the onSocketDidDisconnect delegate method will be called immediately, before this method returns.

- (void)disconnect

Discussion

Disconnects immediately. Any pending reads or writes are dropped. If the socket is not already disconnected, the onSocketDidDisconnect delegate method will be called immediately, before this method returns.

Please note the recommended way of releasing an FMAsyncSocket instance (e.g. in a dealloc method) [asyncSocket setDelegate:nil]; [asyncSocket disconnect]; [asyncSocket release];

Declared In

FM.h

– disconnectAfterReading

Disconnects after all pending reads have completed. After calling this, the read and write methods will do nothing. The socket will disconnect even if there are still pending writes.

- (void)disconnectAfterReading

Discussion

Disconnects after all pending reads have completed. After calling this, the read and write methods will do nothing. The socket will disconnect even if there are still pending writes.

Declared In

FM.h

– disconnectAfterWriting

Disconnects after all pending writes have completed. After calling this, the read and write methods will do nothing. The socket will disconnect even if there are still pending reads.

- (void)disconnectAfterWriting

Discussion

Disconnects after all pending writes have completed. After calling this, the read and write methods will do nothing. The socket will disconnect even if there are still pending reads.

Declared In

FM.h

– disconnectAfterReadingAndWriting

Disconnects after all pending reads and writes have completed. After calling this, the read and write methods will do nothing.

- (void)disconnectAfterReadingAndWriting

Discussion

Disconnects after all pending reads and writes have completed. After calling this, the read and write methods will do nothing.

Declared In

FM.h

– connectedHost

Returns the local or remote host and port to which this socket is connected, or nil and 0 if not connected. The host will be an IP address.

- (NSString *)connectedHost

Discussion

Returns the local or remote host and port to which this socket is connected, or nil and 0 if not connected. The host will be an IP address.

Declared In

FM.h

– connectedAddress

Returns the local or remote address to which this socket is connected, specified as a sockaddr structure wrapped in a NSData object.

- (NSData *)connectedAddress

Discussion

Returns the local or remote address to which this socket is connected, specified as a sockaddr structure wrapped in a NSData object.

See also the connectedHost, connectedPort, localHost and localPort methods.

Declared In

FM.h

– isIPv4

Returns whether the socket is IPv4 or IPv6. An accepting socket may be both.

- (BOOL)isIPv4

Discussion

Returns whether the socket is IPv4 or IPv6. An accepting socket may be both.

Declared In

FM.h

– readDataWithTimeout:tag:

Reads the first available bytes that become available on the socket.

- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag

Discussion

Reads the first available bytes that become available on the socket.

If the timeout value is negative, the read operation will not use a timeout.

Declared In

FM.h

– readDataWithTimeout:buffer:bufferOffset:tag:

Reads the first available bytes that become available on the socket. The bytes will be appended to the given byte buffer starting at the given offset. The given buffer will automatically be increased in size if needed.

- (void)readDataWithTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger)offset tag:(long)tag

Discussion

Reads the first available bytes that become available on the socket. The bytes will be appended to the given byte buffer starting at the given offset. The given buffer will automatically be increased in size if needed.

If the timeout value is negative, the read operation will not use a timeout. If the buffer if nil, the socket will create a buffer for you.

If the bufferOffset is greater than the length of the given buffer, the method will do nothing, and the delegate will not be called.

If you pass a buffer, you must not alter it in any way while FMAsyncSocket is using it. After completion, the data returned in onSocket:didReadData:withTag: will be a subset of the given buffer. That is, it will reference the bytes that were appended to the given buffer.

Declared In

FM.h

– readDataWithTimeout:buffer:bufferOffset:maxLength:tag:

Reads the first available bytes that become available on the socket. The bytes will be appended to the given byte buffer starting at the given offset. The given buffer will automatically be increased in size if needed. A maximum of length bytes will be read.

- (void)readDataWithTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger)offset maxLength:(NSUInteger)length tag:(long)tag

Discussion

Reads the first available bytes that become available on the socket. The bytes will be appended to the given byte buffer starting at the given offset. The given buffer will automatically be increased in size if needed. A maximum of length bytes will be read.

If the timeout value is negative, the read operation will not use a timeout. If the buffer if nil, a buffer will automatically be created for you. If maxLength is zero, no length restriction is enforced.

If the bufferOffset is greater than the length of the given buffer, the method will do nothing, and the delegate will not be called.

If you pass a buffer, you must not alter it in any way while FMAsyncSocket is using it. After completion, the data returned in onSocket:didReadData:withTag: will be a subset of the given buffer. That is, it will reference the bytes that were appended to the given buffer.

Declared In

FM.h

– readDataToLength:withTimeout:tag:

Reads the given number of bytes.

- (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag

Discussion

Reads the given number of bytes.

If the timeout value is negative, the read operation will not use a timeout.

If the length is 0, this method does nothing and the delegate is not called.

Declared In

FM.h

– readDataToLength:withTimeout:buffer:bufferOffset:tag:

Reads the given number of bytes. The bytes will be appended to the given byte buffer starting at the given offset. The given buffer will automatically be increased in size if needed.

- (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger)offset tag:(long)tag

Discussion

Reads the given number of bytes. The bytes will be appended to the given byte buffer starting at the given offset. The given buffer will automatically be increased in size if needed.

If the timeout value is negative, the read operation will not use a timeout. If the buffer if nil, a buffer will automatically be created for you.

If the length is 0, this method does nothing and the delegate is not called. If the bufferOffset is greater than the length of the given buffer, the method will do nothing, and the delegate will not be called.

If you pass a buffer, you must not alter it in any way while FMAsyncSocket is using it. After completion, the data returned in onSocket:didReadData:withTag: will be a subset of the given buffer. That is, it will reference the bytes that were appended to the given buffer.

Declared In

FM.h

– readDataToData:withTimeout:tag:

Reads bytes until (and including) the passed “data” parameter, which acts as a separator.

- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag

Discussion

Reads bytes until (and including) the passed “data” parameter, which acts as a separator.

If the timeout value is negative, the read operation will not use a timeout.

If you pass nil or zero-length data as the “data” parameter, the method will do nothing, and the delegate will not be called.

To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the “data” parameter. Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for a character, the read will prematurely end.

Declared In

FM.h

– readDataToData:withTimeout:buffer:bufferOffset:tag:

Reads bytes until (and including) the passed “data” parameter, which acts as a separator. The bytes will be appended to the given byte buffer starting at the given offset. The given buffer will automatically be increased in size if needed.

- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger)offset tag:(long)tag

Discussion

Reads bytes until (and including) the passed “data” parameter, which acts as a separator. The bytes will be appended to the given byte buffer starting at the given offset. The given buffer will automatically be increased in size if needed.

If the timeout value is negative, the read operation will not use a timeout. If the buffer if nil, a buffer will automatically be created for you.

If the bufferOffset is greater than the length of the given buffer, the method will do nothing, and the delegate will not be called.

If you pass a buffer, you must not alter it in any way while FMAsyncSocket is using it. After completion, the data returned in onSocket:didReadData:withTag: will be a subset of the given buffer. That is, it will reference the bytes that were appended to the given buffer.

To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the “data” parameter. Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for a character, the read will prematurely end.

Declared In

FM.h

– readDataToData:withTimeout:maxLength:tag:

Reads bytes until (and including) the passed “data” parameter, which acts as a separator.

- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout maxLength:(NSUInteger)length tag:(long)tag

Discussion

Reads bytes until (and including) the passed “data” parameter, which acts as a separator.

If the timeout value is negative, the read operation will not use a timeout.

If maxLength is zero, no length restriction is enforced. Otherwise if maxLength bytes are read without completing the read, it is treated similarly to a timeout - the socket is closed with a FMAsyncSocketReadMaxedOutError. The read will complete successfully if exactly maxLength bytes are read and the given data is found at the end.

If you pass nil or zero-length data as the “data” parameter, the method will do nothing, and the delegate will not be called. If you pass a maxLength parameter that is less than the length of the data parameter, the method will do nothing, and the delegate will not be called.

To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the “data” parameter. Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for a character, the read will prematurely end.

Declared In

FM.h

– readDataToData:withTimeout:buffer:bufferOffset:maxLength:tag:

Reads bytes until (and including) the passed “data” parameter, which acts as a separator. The bytes will be appended to the given byte buffer starting at the given offset. The given buffer will automatically be increased in size if needed. A maximum of length bytes will be read.

- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout buffer:(NSMutableData *)buffer bufferOffset:(NSUInteger)offset maxLength:(NSUInteger)length tag:(long)tag

Discussion

Reads bytes until (and including) the passed “data” parameter, which acts as a separator. The bytes will be appended to the given byte buffer starting at the given offset. The given buffer will automatically be increased in size if needed. A maximum of length bytes will be read.

If the timeout value is negative, the read operation will not use a timeout. If the buffer if nil, a buffer will automatically be created for you.

If maxLength is zero, no length restriction is enforced. Otherwise if maxLength bytes are read without completing the read, it is treated similarly to a timeout - the socket is closed with a FMAsyncSocketReadMaxedOutError. The read will complete successfully if exactly maxLength bytes are read and the given data is found at the end.

If you pass a maxLength parameter that is less than the length of the data parameter, the method will do nothing, and the delegate will not be called. If the bufferOffset is greater than the length of the given buffer, the method will do nothing, and the delegate will not be called.

If you pass a buffer, you must not alter it in any way while FMAsyncSocket is using it. After completion, the data returned in onSocket:didReadData:withTag: will be a subset of the given buffer. That is, it will reference the bytes that were appended to the given buffer.

To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the “data” parameter. Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for a character, the read will prematurely end.

Declared In

FM.h

– writeData:withTimeout:tag:

Writes data to the socket, and calls the delegate when finished.

- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag

Discussion

Writes data to the socket, and calls the delegate when finished.

If you pass in nil or zero-length data, this method does nothing and the delegate will not be called. If the timeout value is negative, the write operation will not use a timeout.

Declared In

FM.h

– progressOfReadReturningTag:bytesDone:total:

Returns progress of current read or write, from 0.0 to 1.0, or NaN if no read/write (use isnan() to check). “tag”, “done” and “total” will be filled in if they aren’t NULL.

- (float)progressOfReadReturningTag:(long *)tag bytesDone:(NSUInteger *)done total:(NSUInteger *)total

Discussion

Returns progress of current read or write, from 0.0 to 1.0, or NaN if no read/write (use isnan() to check). “tag”, “done” and “total” will be filled in if they aren’t NULL.

Declared In

FM.h

– startTLS:

Secures the connection using SSL/TLS.

- (void)startTLS:(NSDictionary *)tlsSettings

Discussion

Secures the connection using SSL/TLS.

This method may be called at any time, and the TLS handshake will occur after all pending reads and writes are finished. This allows one the option of sending a protocol dependent StartTLS message, and queuing the upgrade to TLS at the same time, without having to wait for the write to finish. Any reads or writes scheduled after this method is called will occur over the secured connection.

The possible keys and values for the TLS settings are well documented. Some possible keys are: - kCFStreamSSLLevel - kCFStreamSSLAllowsExpiredCertificates - kCFStreamSSLAllowsExpiredRoots - kCFStreamSSLAllowsAnyRoot - kCFStreamSSLValidatesCertificateChain - kCFStreamSSLPeerName - kCFStreamSSLCertificates - kCFStreamSSLIsServer

Please refer to Apple’s documentation for associated values, as well as other possible keys.

If you pass in nil or an empty dictionary, the default settings will be used.

The default settings will check to make sure the remote party’s certificate is signed by a trusted 3rd party certificate agency (e.g. verisign) and that the certificate is not expired. However it will not verify the name on the certificate unless you give it a name to verify against via the kCFStreamSSLPeerName key. The security implications of this are important to understand. Imagine you are attempting to create a secure connection to MySecureServer.com, but your socket gets directed to MaliciousServer.com because of a hacked DNS server. If you simply use the default settings, and MaliciousServer.com has a valid certificate, the default settings will not detect any problems since the certificate is valid. To properly secure your connection in this particular scenario you should set the kCFStreamSSLPeerName property to “MySecureServer.com”. If you do not know the peer name of the remote host in advance (for example, you’re not sure if it will be “domain.com” or “www.domain.com”), then you can use the default settings to validate the certificate, and then use the X509Certificate class to verify the issuer after the socket has been secured. The X509Certificate class is part of the CocoaFMAsyncSocket open source project.

Declared In

FM.h

– enablePreBuffering

For handling readDataToData requests, data is necessarily read from the socket in small increments. The performance can be much improved by allowing FMAsyncSocket to read larger chunks at a time and store any overflow in a small internal buffer. This is termed pre-buffering, as some data may be read for you before you ask for it. If you use readDataToData a lot, enabling pre-buffering will result in better performance, especially on the iPhone.

- (void)enablePreBuffering

Discussion

For handling readDataToData requests, data is necessarily read from the socket in small increments. The performance can be much improved by allowing FMAsyncSocket to read larger chunks at a time and store any overflow in a small internal buffer. This is termed pre-buffering, as some data may be read for you before you ask for it. If you use readDataToData a lot, enabling pre-buffering will result in better performance, especially on the iPhone.

The default pre-buffering state is controlled by the DEFAULT_PREBUFFERING definition. It is highly recommended one leave this set to YES.

This method exists in case pre-buffering needs to be disabled by default for some unforeseen reason. In that case, this method exists to allow one to easily enable pre-buffering when ready.

Declared In

FM.h

– moveToRunLoop:

When you create an FMAsyncSocket, it is added to the runloop of the current thread. So for manually created sockets, it is easiest to simply create the socket on the thread you intend to use it.

- (BOOL)moveToRunLoop:(NSRunLoop *)runLoop

Discussion

When you create an FMAsyncSocket, it is added to the runloop of the current thread. So for manually created sockets, it is easiest to simply create the socket on the thread you intend to use it.

If a new socket is accepted, the delegate method onSocket:wantsRunLoopForNewSocket: is called to allow you to place the socket on a separate thread. This works best in conjunction with a thread pool design.

If, however, you need to move the socket to a separate thread at a later time, this method may be used to accomplish the task.

This method must be called from the thread/runloop the socket is currently running on.

Note: After calling this method, all further method calls to this object should be done from the given runloop. Also, all delegate calls will be sent on the given runloop.

Declared In

FM.h

– setRunLoopModes:

Allows you to configure which run loop modes the socket uses. The default set of run loop modes is NSDefaultRunLoopMode.

- (BOOL)setRunLoopModes:(NSArray *)runLoopModes

Discussion

Allows you to configure which run loop modes the socket uses. The default set of run loop modes is NSDefaultRunLoopMode.

If you’d like your socket to continue operation during other modes, you may want to add modes such as NSModalPanelRunLoopMode or NSEventTrackingRunLoopMode. Or you may simply want to use NSRunLoopCommonModes.

Accepted sockets will automatically inherit the same run loop modes as the listening socket.

Note: NSRunLoopCommonModes is defined in 10.5. For previous versions one can use kCFRunLoopCommonModes.

Declared In

FM.h

– runLoopModes

Returns the current run loop modes the FMAsyncSocket instance is operating in. The default set of run loop modes is NSDefaultRunLoopMode.

- (NSArray *)runLoopModes

Discussion

Returns the current run loop modes the FMAsyncSocket instance is operating in. The default set of run loop modes is NSDefaultRunLoopMode.

Declared In

FM.h

– unreadData

In the event of an error, this method may be called during onSocket:willDisconnectWithError: to read any data that’s left on the socket.

- (NSData *)unreadData

Discussion

In the event of an error, this method may be called during onSocket:willDisconnectWithError: to read any data that’s left on the socket.

Declared In

FM.h