Monday, April 29, 2013

NSFileHandle NSFileHandleConnectionAcceptedNotification example ios


NSFileHandleConnectionAcceptedNotification


This notification is posted when an NSFileHandle object establishes a socket connection between two processes, creates an NSFileHandle object for one end of the connection, and makes this object available to observers by putting it in the userInfo dictionary. To cause the posting of this notification, you must send either acceptConnectionInBackgroundAndNotify or acceptConnectionInBackgroundAndNotifyForModes: to an NSFileHandle object representing a server stream-type socket. [NSFileHandle NSFileHandleConnectionAcceptedNotification]
The notification object is the NSFileHandle object that sent the notification. The userInfodictionary contains the following information:
Key
Value
NSFileHandleNotificationFileHandleItemThe NSFileHandle object representing the “near” end of a socket connection
@"NSFileHandleError"An NSNumber object containing an integer representing the UNIX-type error which occurred
example of [NSFileHandle NSFileHandleConnectionAcceptedNotification]
-(void)createSocket 
{
    // create socket and wait for events to come in
    NSSocketPort* serverSock = [[NSSocketPort alloc] initWithTCPPort: 1234];
    socketHandle = [[NSFileHandle alloc] initWithFileDescriptor: [serverSock socket]
                                                 closeOnDealloc: NO];
// NSFileHandleConnectionAcceptedNotification
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(newConnection:) 
                                                 name: NSFileHandleConnectionAcceptedNotification
                                               object: socketHandle];

    [socketHandle acceptConnectionInBackgroundAndNotify];
}

- (void)newConnection:(NSNotification*)notification
{
    NSLog(@"connection accepted");

    NSDictionary* userInfo = [notification userInfo];
    NSFileHandle* remoteFileHandle = [userInfo objectForKey:
                                      NSFileHandleNotificationFileHandleItem];

    if([[userInfo allKeys] containsObject:@"NSFileHandleError"]){
        NSNumber* errorNo = [userInfo objectForKey:@"NSFileHandleError"];
        if( errorNo ) {
            NSLog(@"NSFileHandle Error: %@", errorNo);
            return;
        }
    }

    [socketHandle acceptConnectionInBackgroundAndNotify];


    [[NSNotificationCenter defaultCenter] addObserver:self 
       selector: @selector(processSocketData:)
           name: NSFileHandleReadCompletionNotification
         object: remoteFileHandle];

    // Send a message to the client, acknowledging that the connection was accepted
    [remoteFileHandle writeData: [@"OK" dataUsingEncoding: NSASCIIStringEncoding]];

    [remoteFileHandle readInBackgroundAndNotify];
}