blob: a65d017b9ce004fc7a36f7ffde9511b2b43654b7 [file] [log] [blame]
Mark Slee77575e62007-09-24 19:24:53 +00001#import <Cocoa/Cocoa.h>
2#import "TSocketServer.h"
3#import "TNSFileHandleTransport.h"
4#import "TProtocol.h"
5
6
7@implementation TSocketServer
8
9- (id) initWithPort: (int) port
10 protocolFactory: (id <TProtocolFactory>) protocolFactory
11 processor: (id <TProcessor>) processor;
12{
13 self = [super init];
14
15 mInputProtocolFactory = [protocolFactory retain];
16 mOutputProtocolFactory = [protocolFactory retain];
17 mProcessor = [processor retain];
18
19 // create a socket
20 mServerSocket = [[NSSocketPort alloc] initWithTCPPort: 8081];
21 // wrap it in a file handle so we can get messages from it
22 mSocketFileHandle = [[NSFileHandle alloc] initWithFileDescriptor: [mServerSocket socket]
23 closeOnDealloc: YES];
24
25 // register for notifications of accepted incoming connections
26 [[NSNotificationCenter defaultCenter] addObserver: self
27 selector: @selector(connectionAccepted:)
28 name: NSFileHandleConnectionAcceptedNotification
29 object: mSocketFileHandle];
30
31 // tell socket to listen
32 [mSocketFileHandle acceptConnectionInBackgroundAndNotify];
33
34 return self;
35}
36
37
38- (void) dealloc {
39 [mInputProtocolFactory release];
40 [mOutputProtocolFactory release];
41 [mProcessor release];
42 [mSocketFileHandle release];
43 [mServerSocket release];
44 [super dealloc];
45}
46
47
48- (void) connentionAccepted: (NSNotification *) aNotification
49{
50 NSFileHandle * socket = [[aNotification userInfo] objectForKey: NSFileHandleNotificationFileHandleItem];
51
52 // now that we have a client connected, spin off a thread to handle activity
53 [NSThread detachNewThreadSelector: @selector(handleClientConnection:)
54 toTarget: self
55 withObject: socket];
56
57 [[aNotification object] acceptConnectionInBackgroundAndNotify];
58}
59
60
61- (void) handleClientConnection: (NSFileHandle *) clientSocket
62{
63 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
64
65 TNSFileHandleTransport * transport = [[TNSFileHandleTransport alloc] initWithFileHandle: clientSocket];
66
67 id <TProtocol> inProtocol = [mInputProtocolFactory newProtocolOnTransport: transport];
68 id <TProtocol> outProtocol = [mOutputProtocolFactory newProtocolOnTransport: transport];
69
70 while ([mProcessor processOnInputProtocol: inProtocol outputProtocol: outProtocol]);
71
72 [pool release];
73}
74
75
76
77@end
78
79
80