1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
|
/* Gridlock
Copyright (c) 2002-2003 by Brian Nenninger. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#import "ServerController.h"
#import "EDTCPSocket.h"
#import "GameController.h"
#import "NetConnection.h"
#import "CocoaAdditions.h"
#import "Preferences.h"
#import "RendezvousUtils.h"
@implementation ServerController
idAccessor(netConnection, setNetConnection)
idAccessor(rendezvousService, setRendezvousService)
-(id)init {
[super init];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(connectionAccepted:)
name:NSFileHandleConnectionAcceptedNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(readPropertyList:)
name:@"NetConnectionReadPropertyListNotification"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(gotNetworkConnection:)
name:@"NetConnectionEstablishedNotification"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(networkConnectionTerminated:)
name:@"NetConnectionTerminatedNotification"
object:nil];
return self;
}
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self setNetConnection:nil];
[super dealloc];
}
-(void)awakeFromNib {
isWindowExpanded = YES;
windowHeightDelta = [windowSizerField frame].origin.y * [window userSpaceScaleFactor_];
[connectionStatusField setStringValue:@"Not listening"];
[self buildGamePopup];
[usernameField setStringValue:[[Preferences sharedInstance] networkUsername]];
[self gameSelectedFromPopup:nil];
[self showWindow];
}
-(void)buildGamePopup {
NSArray *displayNames = [GameConfiguration allGameDisplayNames];
NSArray *names = [GameConfiguration allGameNames];
[gamePopup setItemTitles:displayNames representedObjects_:names];
[gamePopup selectItemAtIndex:0];
}
idAccessor(gameConfiguration, setGameConfiguration)
-(IBAction)gameSelectedFromPopup:(id)sender {
NSString *gameName = [[gamePopup selectedItem] representedObject];
GameConfiguration *newConfig = [[[GameConfiguration alloc] initWithName:gameName variation:nil] autorelease];
NSArray *varDisplayNames = [newConfig allVariationDisplayNames];
if ([varDisplayNames count]>1) {
[variationPopup setItemTitles:varDisplayNames representedObjects_:[newConfig allVariationNames]];
[variationPopup setEnabled:YES];
}
else {
[variationPopup removeAllItems];
[variationPopup addItemWithTitle:NSLocalizedString(@"NoVariationsTitle", nil)];
[variationPopup setEnabled:NO];
}
}
-(void)showWindow {
[self setWindowExpanded:NO display:NO];
[windowSizerField setStringValue:@""];
[window makeKeyAndOrderFront:nil];
}
-(void)setWindowExpanded:(BOOL)isExp display:(BOOL)disp {
if (isExp && !isWindowExpanded) {
// expand
NSRect frame = [window frame];
[window setFrame:NSMakeRect(frame.origin.x, frame.origin.y-windowHeightDelta,
frame.size.width, frame.size.height+windowHeightDelta)
display:disp
animate:YES];
}
else if (!isExp && isWindowExpanded) {
// collapse
NSRect frame = [window frame];
[window setFrame:NSMakeRect(frame.origin.x, frame.origin.y+windowHeightDelta,
frame.size.width, frame.size.height-windowHeightDelta)
display:disp
animate:YES];
}
isWindowExpanded = isExp;
}
-(NSFileHandle *)serverSocket {
return serverSocket;
}
-(void)setServerSocket:(NSFileHandle *)fh {
if (serverSocket!=fh) {
id oldsocket = serverSocket;
serverSocket = [fh retain];
[oldsocket closeFile];
[oldsocket release];
[serverSocket acceptConnectionInBackgroundAndNotify];
}
}
-(NSString *)rendezvousServiceName {
NSMutableArray *fields = [NSMutableArray array];
int i;
[fields addObject:([gamePopup titleOfSelectedItem]) ? [gamePopup titleOfSelectedItem] : @""];
[fields addObject:([variationPopup isEnabled]) ? [variationPopup titleOfSelectedItem] : @""];
[fields addObject:[[Preferences sharedInstance] networkUsername]];
[fields addObject:rendezvousIdentifier_()];
// replace any colons with dashes, join by colons
for(i=0; i<[fields count]; i++) {
id newValue = [[[fields objectAtIndex:i] componentsSeparatedByString:@":"] componentsJoinedByString:@"-"];
[fields replaceObjectAtIndex:i withObject:newValue];
}
return [fields componentsJoinedByString:@":"];
}
-(BOOL)publishRendezvousServiceOnPort:(int)port {
if (isRendezvousAvailable_()) {
id service = [[[nsNetServiceClass_() alloc] initWithDomain:@""
type:@"_gridlock._tcp"
name:[self rendezvousServiceName]
port:port] autorelease];
[self setRendezvousService:service];
[service setDelegate:self];
[service publish];
return YES;
}
return NO;
}
- (IBAction)beginHosting:(id)sender {
int port = 0;
[self updateUsername:nil];
if ([self serverSocket]) return;
NS_DURING
EDTCPSocket *sock = [EDTCPSocket socket];
port = [portField intValue];
[sock startListeningOnLocalPort:port];
[self setServerSocket:sock];
[self publishRendezvousServiceOnPort:port];
NS_HANDLER
[self setServerSocket:nil];
[connectionStatusField setStringValue:[NSString stringWithFormat:@"Unable to listen on port %d",port]];
NS_ENDHANDLER
if ([self serverSocket]) {
[connectionStatusField setStringValue:[NSString stringWithFormat:@"Listening on port %d",port]];
}
}
-(void)connectionAccepted:(NSNotification *)notification {
if ([self serverSocket]==[notification object]) {
NSFileHandle *clientSocket = [[notification userInfo] objectForKey:NSFileHandleNotificationFileHandleItem];
if (clientSocket) {
//[connectionStatusField setStringValue:@"Got connection"];
//[self setWindowExpanded:YES display:YES];
[self setNetConnection:[NetConnection connectionWithSocket:clientSocket]];
// wait for connect request from client
}
}
}
- (IBAction)abortHosting:(id)sender {
[self setServerSocket:nil];
[self setNetConnection:nil];
[[self rendezvousService] stop];
[connectionStatusField setStringValue:@"Not listening"];
//[self setWindowExpanded:NO display:NO];
}
-(IBAction)updateUsername:(id)sender {
[[Preferences sharedInstance] setNetworkUsername:[usernameField stringValue]];
}
- (IBAction)startGame:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:@"NetConnectionEstablishedNotification" object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[self gameConfiguration], @"configuration", [self netConnection], @"connection", [NSNumber numberWithInt:2], @"playerNumber", nil]];
[self abortHosting:nil];
[window orderOut:nil];
}
-(void)readPropertyList:(NSNotification *)notification {
if ([self netConnection]==[notification object]) {
id plist = [[notification userInfo] objectForKey:@"plist"];
if ([plist objectForKey:@"connect"]) {
NSString *username = [plist objectForKey:@"username"];
NSString *password = [plist objectForKey:@"password"];
NSString *requiredPassword = [passwordField stringValue];
if (([password length]==0 && [requiredPassword length]==0) || [password isEqual:requiredPassword]) {
GameConfiguration *config = [[[GameConfiguration alloc] initWithName:[[gamePopup selectedItem] representedObject] variation:[[variationPopup selectedItem] representedObject]] autorelease];
NSMutableDictionary *startDict = [NSMutableDictionary dictionary];
[[self netConnection] setRemoteUsername:username];
[self setGameConfiguration:config];
[startDict setObject:@"" forKey:@"start"];
[startDict setObject:[[self gameConfiguration] propertyList] forKey:@"configuration"];
[startDict setObject:[[Preferences sharedInstance] networkUsername] forKey:@"username"];
[[self netConnection] transmitPropertyList:startDict];
// todo: require confirmation from both players before starting
// stop listening
[self setServerSocket:nil];
[self startGame:nil];
}
else {
// bad password
// because of complex object graph interactions, we need to delay sending the failure message
// and disconnecting until the next cycle of the run loop
[self performSelector:@selector(handleFailedConnect) withObject:nil afterDelay:0.0];
}
}
}
}
-(void)handleFailedConnect {
NSMutableDictionary *failDict = [NSMutableDictionary dictionary];
[failDict setObject:@"" forKey:@"refused"];
[[self netConnection] transmitPropertyList:failDict];
[self setNetConnection:nil];
[[self serverSocket] acceptConnectionInBackgroundAndNotify];
}
// called when a connection is established (could be from connecting by this window or from client)
-(void)gotNetworkConnection:(NSNotification *)notification {
[self abortHosting:nil];
[window orderOut:nil];
}
// called when connection is terminated (probably due to invalid input)
-(void)networkConnectionTerminated:(NSNotification *)notification {
if ([notification object]==[self netConnection]) {
[self setNetConnection:nil];
[[self serverSocket] acceptConnectionInBackgroundAndNotify];
}
}
-(void)windowWillClose:(NSNotification *)notification {
if (window==[notification object]) {
[self abortHosting:nil];
}
}
// Rendezvous delegate methods
-(void)netServiceWillPublish:(id)service {
NSLog(@"Rendezvous service published");
}
-(void)netService:(id)service didNotPublish:(NSDictionary *)errorDict {
}
-(void)netServiceDidStop:(id)service {
NSLog(@"Rendezvous service stopped");
}
@end
|