On Mar 19, 2008, at 5:58 AM, Valentin Dan wrote:
I need to send and receive message over the network but I got stuck …


Surprisingly, there is no general-purpose Cocoa wrapper for the CFNetwork foundation functions. There are several specific wrappers - such as NSURLConnection and NSURLDownload, but if you want to do low- level socket communication with a protocol other than HTTP or FTP, you're going to have to get your hands a little dirty.

You always have the option of using BSD Sockets, of course, if you want to go old school. Or you can use the CFNetwork functions. There are a few Objective-C wrappers provided by third parties, including AsyncSockets, SimpleSockets, and NetSockets, but if you're going to be doing a lot of network communication in your application, I would recommend diving in and really learning the way CFNetwork functionality works. Even though it's implemented with C functions rather than Objective-C classes, it still has a lot of really nice functionality, and since it's the basis for most (all?) of the Cocoa networking classes, it's very robust and well-tested. It offers run loop integration which allows you to keep from blocking without having to detach threads . It's conceptually a little hard to wrap your head around the way it works, but overall, it's probably your best bet unless your needs are relatively simple, in which case something like SimpleSockets is probably the way to go.

http://developer.apple.com/documentation/Networking/Conceptual/CFNetwork/Introduction/chapter_1_section_1.html

Here's a little trick for integrating the C callback functions into your objective-C method. When you create your CFStreamClientContext, pass a pointer to self in the second argument. Whatever you pass there will get passed back to your callback function Then, in your callback function, you can do something like this:

void readStreamCallBack(CFReadStreamRef stream, CFStreamEventType type, void *controller)
{
        id  self = (id)controller;
        ...

If you do that, you can then makes calls against self just as you would in one of your instance methods. The only other real gotcha is that you have to implement a buffering scheme. The information comes in chunks on the read stream, and on the write stream, you sometimes have to wait and yield to the run loop before you're able to write, and sometimes have to write in chunks. If you do not pass control back to the run loop when the stream is not ready, it will never be ready.

Hope this helps,
Jeff

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to