Index: src/OFTCPSocket.h ================================================================== --- src/OFTCPSocket.h +++ src/OFTCPSocket.h @@ -31,11 +31,16 @@ #ifdef _WIN32 # include #endif +@class OFTCPSocket; @class OFString; + +#ifdef OF_HAVE_BLOCKS +typedef void (^of_tcpsocket_async_connect_block_t)(OFTCPSocket*); +#endif /** * \brief A class which provides functions to create and use TCP sockets. * * To connect to a server, create a socket and connect it. @@ -120,10 +125,23 @@ * \param host The host to connect to * \param port The port on the host to connect to */ - (void)connectToHost: (OFString*)host port: (uint16_t)port; + +#ifdef OF_HAVE_BLOCKS +/** + * \brief Asyncronously connect the OFTCPSocket to the specified destination. + * + * \param host The host to connect to + * \param port The port on the host to connect to + * \param block The block to execute once the connection has been established + */ +- (void)asyncConnectToHost: (OFString*)host + port: (uint16_t)port + block: (of_tcpsocket_async_connect_block_t)block; +#endif /** * \brief Bind the socket on the specified port and host. * * \param host The host to bind to. Use @"0.0.0.0" for IPv4 or @"::" for IPv6 Index: src/OFTCPSocket.m ================================================================== --- src/OFTCPSocket.m +++ src/OFTCPSocket.m @@ -33,10 +33,13 @@ #endif #import "OFTCPSocket.h" #import "OFTCPSocket+SOCKS5.h" #import "OFString.h" +#import "OFThread.h" +#import "OFTimer.h" +#import "OFRunLoop.h" #import "OFAcceptFailedException.h" #import "OFAlreadyConnectedException.h" #import "OFAddressTranslationFailedException.h" #import "OFBindFailedException.h" @@ -283,10 +286,44 @@ if (SOCKS5Host != nil) [self _SOCKS5ConnectToHost: destinationHost port: destinationPort]; } + +#ifdef OF_HAVE_BLOCKS +- (void)asyncConnectToHost: (OFString*)host + port: (uint16_t)port + block: (of_tcpsocket_async_connect_block_t)block +{ + void *pool = objc_autoreleasePoolPush(); + OFRunLoop *runLoop = [OFRunLoop currentRunLoop]; + + [[OFThread threadWithObject: self + block: ^ (id s) { + void *pool2 = objc_autoreleasePoolPush(); + OFThread *connectThread = [OFThread currentThread]; + OFTimer *timer; + + [s connectToHost: host + port: port]; + + timer = [OFTimer timerWithTimeInterval: 0 + repeats: NO + block: ^ { + [connectThread join]; + block(s); + }]; + [runLoop addTimer: timer]; + + objc_autoreleasePoolPop(pool2); + + return nil; + }] start]; + + objc_autoreleasePoolPop(pool); +} +#endif - (uint16_t)bindToHost: (OFString*)host port: (uint16_t)port { union {