BLIP/Demo/BLIPEchoServer.m
author Jens Alfke <jens@mooseyard.com>
Fri Jul 24 14:06:28 2009 -0700 (2009-07-24)
changeset 63 5e4855a592ee
parent 26 cb9cdf247239
permissions -rw-r--r--
* The BLIPConnection receivedRequest: delegate method now returns BOOL. If the method returns NO (or if the method isn't implemented in the delegate), that means it didn't handle the message at all; an error will be returned to the sender.
* If the connection closes unexpectedly due to an error, then the auto-generated responses to pending requests will contain that error. This makes it easier to display a meaningful error message in the handler for the request.
     1 //
     2 //  BLIPEchoServer.m
     3 //  MYNetwork
     4 //
     5 //  Created by Jens Alfke on 5/24/08.
     6 //  Copyright 2008 Jens Alfke. All rights reserved.
     7 //
     8 
     9 #import "BLIPEchoServer.h"
    10 #import "MYNetwork.h"
    11 
    12 
    13 @implementation BLIPEchoServer
    14 
    15 
    16 - (id) init
    17 {
    18     self = [super init];
    19     if (self != nil) {
    20         _listener = [[BLIPListener alloc] initWithPort: 12345];
    21         _listener.delegate = self;
    22         _listener.pickAvailablePort = YES;
    23         _listener.bonjourServiceType = @"_blipecho._tcp";
    24         [_listener open];
    25         NSLog(@"%@ is listening...",self);
    26     }
    27     return self;
    28 }
    29 
    30 - (void) dealloc
    31 {
    32     [_listener close];
    33     [_listener release];
    34     [super dealloc];
    35 }
    36 
    37 - (void) listener: (TCPListener*)listener failedToOpen: (NSError*)error
    38 {
    39     NSLog(@"** %@ failed to open: %@",self,error);
    40 }
    41 
    42 - (void) listener: (TCPListener*)listener didAcceptConnection: (TCPConnection*)connection
    43 {
    44     NSLog(@"** %@ accepted %@",self,connection);
    45     connection.delegate = self;
    46 }
    47 
    48 - (void) connection: (TCPConnection*)connection failedToOpen: (NSError*)error
    49 {
    50     NSLog(@"** %@ failedToOpen: %@",connection,error);
    51 }
    52 
    53 - (BOOL) connection: (BLIPConnection*)connection receivedRequest: (BLIPRequest*)request
    54 {
    55     NSLog(@"***** %@ received %@",connection,request);
    56     [request respondWithData: request.body contentType: request.contentType];
    57     return YES;
    58 }
    59 
    60 
    61 @end
    62 
    63 
    64 int main( int argc, const char **argv )
    65 {
    66     NSAutoreleasePool *pool = [NSAutoreleasePool new];
    67     BLIPEchoServer *listener = [[BLIPEchoServer alloc] init];
    68     [[NSRunLoop currentRunLoop] run];
    69     [listener release];
    70     [pool drain];
    71 }