Re: Using NSFileHandle for server socket communication
Re: Using NSFileHandle for server socket communication
- Subject: Re: Using NSFileHandle for server socket communication
- From: Alastair Houghton <email@hidden>
- Date: Fri, 12 Dec 2003 09:04:02 +0000
On 12 Dec 2003, at 01:18, Mark Walker wrote:
>
-(void)startClient
>
{
>
NSLog(@"startClient called");
>
>
NSSocketPort *sockPort;
>
sockPort = [[NSSocketPort alloc] initRemoteWithTCPPort:12345
>
host:@"mark-walkers-computer"];
NSSocketPort is really for Distributed Objects. Whilst this will work,
and is an interesting short-cut, I don't think it's really the right
way to go about things. Try something like:
int sockFD = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in sin;
struct hostent *he;
if (sockFD < 0) {
NSLog (@"%s\n", strerror (errno));
return;
}
sin.sin_family = AF_INET;
sin.sin_port = htons (12345);
he = gethostbyname ("mark-walkers-computer");
if (!he) {
NSLog (@"%s\n", hsterror (h_errno));
close (sockFD);
return;
}
memcpy(&sin.sin_addr, he->h_addr, 4);
if (connect (sockFD, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
NSLog (@"%s\n", strerror (errno));
close (sockFD);
return;
}
You should get a fairly specific error message if something goes awry.
There are plenty of books that will explain how to use the sockets
APIs; you should probably get one of them to read.
Note also that in the above code, the gethostbyname() function and the
connect() function can both block for some time trying to resolve the
hostname and then contact the host.
You could also consider using the CFSocket or CFStream APIs to manage
your socket for you; CFStream in particular has a function
CFStreamCreatePairWithSocketToHost(), which looks pretty useful.
(Also, CFStream has a Cocoa counterpart, NSStream, in Panther.) The
major benefit of CFSocket/CFStream/NSStream is that they work through
the run-loop and can do non-blocking *writes* as well as non-blocking
reads, which, as you have probably noticed, NSFileHandle cannot.
Kind regards,
Alastair.
[demime 0.98b removed an attachment of type application/pkcs7-signature which had a name of smime.p7s]
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.