开发者

simple asynchonous client using CFSocket

开发者 https://www.devze.com 2023-04-12 10:01 出处:网络
Also I\'m familiar with BSD sockets, I\'m new to Obj-C and Cocoa so bear with me :) What I\'m trying is a simple TCP client in a console application which just receives data in the background. I woul

Also I'm familiar with BSD sockets, I'm new to Obj-C and Cocoa so bear with me :)

What I'm trying is a simple TCP client in a console application which just receives data in the background. I would like to use CFSockets for this because of the convenient callback functions (implementing it with plain开发者_如何学运维 sockets in an autonomous thread won't be a problem but I want to do this in the Mac way).

Where I'm stuck is, how to use the callback functions without a RunLoop or how to make the RunLoop run in a non blocking manner. As far as I understand, it is not possible to put the RunLoop into the GCD (at least I tried it and the loop never run). So what are the alternatives? Is it possible to run the RunLoop in a NSThread? any more simple way?

Here is the code snipplet that I use. It works fine as single task.

CFSocketRef TCPClient;
CFSocketContext CTX = { 0, "MYCLIENT", NULL, NULL, NULL };
TCPClient = CFSocketCreate(NULL, PF_INET, SOCK_STREAM, IPPROTO_TCP,
    kCFSocketReadCallBack, (CFSocketCallBack)ConnectCallBack, &CTX);
[...]
CFDataRef connectAddr = CFDataCreate(NULL, (unsigned char *)&addr, sizeof(addr));
CFSocketConnectToAddress(TCPClient, connectAddr, −1);
CFRunLoopSourceRef sourceRef = CFSocketCreateRunLoopSource(kCFAllocatorDefault, TCPClient, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), sourceRef, kCFRunLoopCommonModes);
CFRelease(sourceRef);
CFRunLoopRun();

Thanks in advance! Thomas


I recommend AsyncSocket, an objective c lightweight framework (just a couple of files), with optional GDC, very well coded in very much the mac way.

AsyncSocket is a TCP/IP socket networking library that wraps CFSocket and CFStream. It offers asynchronous operation, and a native cocoa class complete with delegate support.

You can configure it (through delegate methods) to use the current run loop or any other run loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消