1 #import <Cocoa/Cocoa.h>
2 #import "TSocketServer.h"
3 #import "TNSFileHandleTransport.h"
5 #import "TTransportException.h"
8 @implementation TSocketServer
10 - (id) initWithPort: (int) port
11 protocolFactory: (id <TProtocolFactory>) protocolFactory
12 processor: (id <TProcessor>) processor;
16 mInputProtocolFactory = [protocolFactory retain];
17 mOutputProtocolFactory = [protocolFactory retain];
18 mProcessor = [processor retain];
21 mServerSocket = [[NSSocketPort alloc] initWithTCPPort: port];
22 // FIXME - move this separate start method and add method to close
23 // and cleanup any open ports
25 if (mServerSocket == nil) {
26 NSLog(@"Unable to listen on TCP port %d", port);
28 NSLog(@"Listening on TCP port %d", port);
30 // wrap it in a file handle so we can get messages from it
31 mSocketFileHandle = [[NSFileHandle alloc] initWithFileDescriptor: [mServerSocket socket]
34 // register for notifications of accepted incoming connections
35 [[NSNotificationCenter defaultCenter] addObserver: self
36 selector: @selector(connectionAccepted:)
37 name: NSFileHandleConnectionAcceptedNotification
38 object: mSocketFileHandle];
40 // tell socket to listen
41 [mSocketFileHandle acceptConnectionInBackgroundAndNotify];
49 [mInputProtocolFactory release];
50 [mOutputProtocolFactory release];
52 [mSocketFileHandle release];
53 [mServerSocket release];
58 - (void) connectionAccepted: (NSNotification *) aNotification
60 NSFileHandle * socket = [[aNotification userInfo] objectForKey: NSFileHandleNotificationFileHandleItem];
62 // now that we have a client connected, spin off a thread to handle activity
63 [NSThread detachNewThreadSelector: @selector(handleClientConnection:)
67 [[aNotification object] acceptConnectionInBackgroundAndNotify];
71 - (void) handleClientConnection: (NSFileHandle *) clientSocket
73 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
75 TNSFileHandleTransport * transport = [[TNSFileHandleTransport alloc] initWithFileHandle: clientSocket];
77 id <TProtocol> inProtocol = [mInputProtocolFactory newProtocolOnTransport: transport];
78 id <TProtocol> outProtocol = [mOutputProtocolFactory newProtocolOnTransport: transport];
81 while ([mProcessor processOnInputProtocol: inProtocol outputProtocol: outProtocol]);
83 @catch (TTransportException * te) {