Re: Server implementation questions
Re: Server implementation questions
- Subject: Re: Server implementation questions
- From: Aram Greenman <email@hidden>
- Date: Thu, 3 Apr 2003 18:18:00 -0800
On Thursday, April 3, 2003, at 03:14 PM, Chris Hanson wrote:
*** Question 1: How do I determine if an NSFileHandle I'm reading
from has available data *without* blocking?
Use select() on the socket file descriptor:
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
@implementation NSFileHandle (Additions)
- (BOOL)isReadable {
int fd = [self fileDescriptor];
fd_set fdset;
struct timeval tmout = { 0, 0 }; // return immediately
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
return select(fd + 1, &fdset, NULL, NULL, &tmout) > 0;
}
@end
Will using -[NSFileHandle readDataOfLength:] to read 0 bytes return
nil immediately for a closed socket
No, it will raise an NSFileHandleOperationException.
and an empty NSData immediately for an open socket regardless of
whether data is available?
Yes, but remember an empty NSData also indicates EOF.
*** Question 2: How should I go about writing code that, from the
same application, connects to the server *without* the headache of
using threads?
Use CFSocket, or one of these Obj-C CFSocket wrappers:
NetSocket <
http://www.blackholemedia.com/>
AsyncSocket <
http://homepage.mac.com/d.j.v./>
AGSocket <
http://sourceforge.net/projects/agkit>
*** Bonus Question 1: If the answer to Question 2 is "You need to use
a separate thread for the server," it means I'm going to have to write
a bunch of raw socket code (or use one of the many wrapper classes).
That's not a huge problem, but how can I shut down the server while
it's listening? If I close(2) the listening/accepting file descriptor
from within the main thread, will accept(2) just return -1 in the
server thread?
There might be a race condition here, i.e., what happens if you close()
a socket just as it accepts a connection? You could use select() again:
BOOL shouldClose = NO; // shared variable
NSFileHandle *socketHandle, *childHandle;
// ... set up listening socket
int fd = [socketHandle fileDescriptor];
fd_set fdset;
struct timeval tmout = { 1, 0 }; // check shouldClose every second
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
while (!shouldClose)
if (select(fd + 1, &fdset, NULL, NULL, &tmout) > 0)
childHandle = [[NSFileHandle alloc] initWithFileDescriptor:accept(fd,
NULL, 0)];
Aram
_______________________________________________
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.