Skip navigation.
 
mlRe: Network communication with NSFileHandle & NSSocketPort
FROM : Chris Parker
DATE : Wed Mar 19 19:27:52 2008

On 19 Mar 2008, at 11:01 AM, Jeff LaMarche wrote:
>
> On Mar 19, 2008, at 1:57 PM, Sherm Pendley wrote:
>

>> Hmmm... Actually, now that I'm looking a second time, it looks like 
>> you need to call both socket() to create the socket, then connect() 
>> to connect to a remote host as a client. Then you can use 
>> NSFileHandle to do the reading and writing.
>>
>> For a server, you can use socket() to create the socket, then 
>> NSFileHandle's -acceptConnectionInBackgroundAndNotify to accept 
>> client connections.
>>
>> It strikes me as kind of odd that NSFileHandle doesn't have an 
>> initializer that wraps the socket() or methods to wrap connect() or 
>> listen(), but it *does* have a wrapper method for accept(). Time to 
>> file a feature request, I think. :-)

>
>
> Do you think this would work as an alternative?
>
> NSSocketPort *port = [[NSSocketPort alloc] 
> initRemoteWithTCPPort:portNum host:@"theserver.com"];
> int fd = [port socket];
> NSFileHandle *fh = [[NSFileHandle alloc] initWithFileDescriptor:fd];


There's some sample code here:

   http://developer.apple.com/samplecode/CocoaEcho/

which shows how to set up an IPv4/IPv6 server with Bonjour publishing 
that uses the NS*Stream classes to do its work.

Doing the server stuff with NSFileHandle is possible (I did it that 
way for the Picture Sharing code) but the CocoaEcho example gets you 
most of the way to having a server set up for you. :)

Please file bugs against the docs or sample code if there are things 
you'd like to see it do that it doesn't today.

.chris

--
Chris Parker
Cocoa Frameworks
Apple Inc.