Skip navigation.
 
mlRe: Network communication with NSFileHandle & NSSocketPort
FROM : Jeff LaMarche
DATE : Wed Mar 19 21:38:16 2008

On Mar 19, 2008, at 4:31 PM, Sherm Pendley wrote:

> Looks reasonable. Now if I could only figure out why I forgot about 
> NSSocketPort...
>
> I think maybe I need to write a network app to jog my memory. 
> Obviously I haven't looked at these classes recently enough. :-)


I couldn't get it to work. Apple's documentation makes it sound like 
NSSocketPort can work for general network sockets, but a little 
Googling led me to some old postings that say it was really only ever 
designed for use with DO and doesn't work as advertised as a full-
service socket wrapper.

I did get the process as you described working fine in a little test 
app, except for one thing - I can only get it to work if I provide the 
address as dot separated octets, like:

   NSString *address = @"66.250.146.128";
   
   struct sockaddr_in addr;
   bzero( &addr, sizeof(struct sockaddr_in));
         addr.sin_family = AF_INET;
   addr.sin_addr.s_addr = inet_addr([address UTF8String]);
   addr.sin_port = htons( 119 );

         int fd = socket( AF_INET, SOCK_STREAM, 0 );
   
   
   if ( connect( fd, (struct sockaddr *)&addr,  sizeof(addr)) < 0 )
   {
       NSLog(@"Error connecting");
       return;
   }
   
   self.fh =[[[NSFileHandle alloc] initWithFileDescriptor:fd] 
autorelease];
   [fh writeData:[@"LIST NEWSGROUPS\r\n" dataUsingEncoding: 
NSUTF8StringEncoding]];
   [fh readInBackgroundAndNotify];
   NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
   [nc addObserver:self selector:@selector(finish:) 
name:NSFileHandleReadToEndOfFileCompletionNotification object:fh];
   [nc addObserver:self selector:@selector(process:) 
name:NSFileHandleReadCompletionNotification object:fh];

But I'm darned if I can figure out how to get it to work with a 
hostname (like @"apple.com"). I've tried using gethostbyname and a few 
other things I've found on the web, but nothing seems to work except 
using the octet string, although I'm sure that's just because I 
haven't worked with sockets in years and am forgetting something 
really stupid. :)

Thanks for all the help.
Jeff