From 9e4ebe074b181c76d55d81d592fcfa1f0a33aeaf Mon Sep 17 00:00:00 2001 From: Robbie Hanson Date: Sat, 4 Jun 2011 14:07:08 -0400 Subject: [PATCH] Fixes issue #53 - allow stopping the server but keeping current connections alive --- HTTPServer.h | 29 ++++++++++++++++++++++++++++- HTTPServer.m | 42 ++++++++++++++++++++++++------------------ 2 files changed, 52 insertions(+), 19 deletions(-) diff --git a/HTTPServer.h b/HTTPServer.h index a975fbcb..848d391b 100644 --- a/HTTPServer.h +++ b/HTTPServer.h @@ -162,8 +162,35 @@ - (NSDictionary *)TXTRecordDictionary; - (void)setTXTRecordDictionary:(NSDictionary *)dict; +/** + * Attempts to starts the server on the configured port, interface, etc. + * + * If an error occurs, this method returns NO and sets the errPtr (if given). + * Otherwise returns YES on success. + * + * Some examples of errors that might occur: + * - You specified the server listen on a port which is already in use by another application. + * - You specified the server listen on a port number below 1024, which requires root priviledges. + * + * Code Example: + * + * NSError *err = nil; + * if (![httpServer start:&err]) + * { + * NSLog(@"Error starting http server: %@", err); + * } +**/ - (BOOL)start:(NSError **)errPtr; -- (BOOL)stop; + +/** + * Stops the server, preventing it from accepting any new connections. + * You may specify whether or not you want to close the existing client connections. + * + * The default stop method (with no arguments) will close any existing connections. (It invokes [self stop:NO]) +**/ +- (void)stop; +- (void)stop:(BOOL)keepExistingConnections; + - (BOOL)isRunning; - (void)addWebSocket:(WebSocket *)ws; diff --git a/HTTPServer.m b/HTTPServer.m index a1f82a78..bed2ac5e 100644 --- a/HTTPServer.m +++ b/HTTPServer.m @@ -448,7 +448,12 @@ - (BOOL)start:(NSError **)errPtr return success; } -- (BOOL)stop +- (void)stop +{ + [self stop:NO]; +} + +- (void)stop:(BOOL)keepExistingConnections { HTTPLogTrace(); @@ -462,28 +467,29 @@ - (BOOL)stop [asyncSocket disconnect]; isRunning = NO; - // Now stop all HTTP connections the server owns - [connectionsLock lock]; - for (HTTPConnection *connection in connections) - { - [connection stop]; - } - [connections removeAllObjects]; - [connectionsLock unlock]; - - // Now stop all WebSocket connections the server owns - [webSocketsLock lock]; - for (WebSocket *webSocket in webSockets) + if (!keepExistingConnections) { - [webSocket stop]; + // Stop all HTTP connections the server owns + [connectionsLock lock]; + for (HTTPConnection *connection in connections) + { + [connection stop]; + } + [connections removeAllObjects]; + [connectionsLock unlock]; + + // Stop all WebSocket connections the server owns + [webSocketsLock lock]; + for (WebSocket *webSocket in webSockets) + { + [webSocket stop]; + } + [webSockets removeAllObjects]; + [webSocketsLock unlock]; } - [webSockets removeAllObjects]; - [webSocketsLock unlock]; [pool drain]; }); - - return YES; } - (BOOL)isRunning