CocoaHTTPServer icon indicating copy to clipboard operation
CocoaHTTPServer copied to clipboard

HTTPServer should only observe notifications relevant to its own instance

Open colemancda opened this issue 10 years ago • 0 comments

in HTTPServer.m, under the -init method

// Register for notifications of closed connections
[[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(connectionDidDie:)
                                                     name:HTTPConnectionDidDieNotification
                                                   object:nil];

// Register for notifications of closed websocket connections
[[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(webSocketDidDie:)
                                                     name:WebSocketDidDieNotification
                                                   object:nil];

Which calls

/**
 * This method is automatically called when a notification of type HTTPConnectionDidDieNotification is posted.
 * It allows us to remove the connection from our array.
**/
- (void)connectionDidDie:(NSNotification *)notification
{
    // Note: This method is called on the connection queue that posted the notification

    [connectionsLock lock];

    HTTPLogTrace();
    [connections removeObject:[notification object]];

    [connectionsLock unlock];
}

/**
 * This method is automatically called when a notification of type WebSocketDidDieNotification is posted.
 * It allows us to remove the websocket from our array.
**/
- (void)webSocketDidDie:(NSNotification *)notification
{
    // Note: This method is called on the connection queue that posted the notification

    [webSocketsLock lock];

    HTTPLogTrace();
    [webSockets removeObject:[notification object]];

    [webSocketsLock unlock];
}

While this code is perfectly legal and will not cause any error if a app has multiple HTTPServer instances, the original [NSNotificationCenter -addObserver: selector: name: object: ] call should include the server as the method's object: argument to reduce the overhead that [NSMutableArray -removeObject:] will cause (and the locking).

Apple docs (https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/removeObject:)

If the array does not contain anObject, the method has no effect (although it does incur the overhead of searching the contents).

colemancda avatar Jun 29 '14 03:06 colemancda