0

ここのAppleのドキュメントに正確に従ってください:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Streams/Streams.html - データを書き込むためのネットワークNSOutputStreamを取得できません。Apple のドキュメントでは返すべきではないと思われる数値を常に返します (0 - Apple は、これはネットワーク ストリームではなく、固定サイズのストリーム用であると主張しています??)。

Apple のサンプル コードはすべてリターン コードを無視します (それが正であると想定しているようです - Web で見つけた多くのサンプルは unsigned 型を使用しています!これは非常に間違っています :( )。

私は成功しました:

  1. kCFSocketAcceptCallBack と handleConnect 関数へのポインターを使用した CFSocketCreate()
  2. 「any」と手動で選択したポートを指定した CFSocketSetAddress()
  3. CFRunLoopAddSource() でポートのリッスンを開始

...これはすべて機能し、IPアドレス+ポートへのtelnetで確認されました...


...しかし、Appleのドキュメントに従うだけで、それはひどく間違っています:

void handleConnect (
                 CFSocketRef s,
                 CFSocketCallBackType callbackType,
                 CFDataRef address,
                 const void *data,
                 void *info
                 )
{
    NSLog(@"handleConnect called with callbackType = %li", callbackType);

    (myclass) server = (myclass*) info;

    BOOL canAccept = callbackType & kCFSocketAcceptCallBack;
    BOOL canWrite = callbackType & kCFSocketWriteCallBack;
    BOOL canRead = callbackType & kCFSocketReadCallBack;
    NSLog(@" ... acceptable? %@  .. readable? %@ .. writeable? %@", canAccept?@"yes":@"no", canRead?@"yes":@"no", canWrite?@"yes":@"no" );

    if( canAccept)
    {
        NSLog(@"[%@] Accepted a socket connection from remote host. Address = %@", [server class], addressString );
        /**
         "which means that a new connection has been accepted. In this case, the data parameter of the callback is a pointer to a CFSocketNativeHandle value (an integer socket number) representing the socket.

         To handle the new incoming connections, you can use the CFStream, NSStream, or CFSocket APIs. The stream-based APIs are strongly recommended."
         */

        // "1. Create read and write streams for the socket with the CFStreamCreatePairWithSocket function."
        CFReadStreamRef clientInput = NULL;
        CFWriteStreamRef clientOutput = NULL;

        // for an AcceptCallBack, the data parameter is a pointer to a CFSocketNativeHandle
        CFSocketNativeHandle nativeSocketHandle = *(CFSocketNativeHandle *)data;

        CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &clientInput, &clientOutput);

        // "2. Cast the streams to an NSInputStream object and an NSOutputStream object if you are working in Cocoa."

        // "3. Use the streams as described in “Writing a TCP-Based Client.”
        self.outputBuffer = [NSMutableData dataWithData:[@"Hello" dataWithEncoding:NSUTF8StringEncoding]];
        self.outputBytesWrittenRecently = 0;
        ((NSOutputStream*)output).delegate = self;

        [((NSOutputStream*)output) scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [((NSOutputStream*)output) open]; // MUST go last, undocumented Apple bug
    }
}

...そしてデリゲートメソッド:

-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    BOOL streamOpened = eventCode & NSStreamEventOpenCompleted;
    BOOL streamReadyToWrite = eventCode & NSStreamEventHasSpaceAvailable;
    BOOL streamReadyToRead = eventCode & NSStreamEventHasBytesAvailable;
    BOOL streamEnded = eventCode & NSStreamEventEndEncountered;
    BOOL streamErrored = eventCode & NSStreamEventErrorOccurred;

    if( streamReadyToWrite )
#define C_BUFFER_IN_MEMORY_SIZE_WRITE ( 4096 ) // Apple vaguely recommends 4k, but I tried numbers down to 100 with no effect
    uint8_t extraCBufferNSStreamSucks[ C_BUFFER_IN_MEMORY_SIZE_WRITE ];
    NSRange rangeOfBytesToAttemptToWriteNext = { self.outputBytesWrittenRecently, MIN( C_BUFFER_IN_MEMORY_SIZE_WRITE, self.outputBuffer.length - self.outputBytesWrittenRecently) };
    [self.outputBuffer getBytes:&extraCBufferNSStreamSucks range:rangeOfBytesToAttemptToWriteNext];

    NSLog(@"About to write data to stream, this might block...");
    NSInteger amountWritten = [self.outputS write:extraCBufferNSStreamSucks maxLength:C_BUFFER_IN_MEMORY_SIZE_WRITE];
    NSLog(@"...finished write data to stream, it might have blocked");
    if( amountWritten > 0 )
    {
        self.outputBytesWrittenRecently += amountWritten;

        NSRange totalWrittenRange = { 0, self.outputBytesWrittenRecently };
        NSLog(@"Written %i bytes: %@", amountWritten, [[[NSString alloc] initWithData:[self.outputBuffer subdataWithRange:totalWrittenRange] encoding:NSUTF8StringEncoding] autorelease] );

        if( self.outputBytesWrittenRecently == self.outputBuffer.length )
        {
            NSLog(@"Finished writing data!");

        }
    }
    else
        NSLog(@"ERROR: failed to write bytes to stream (bytes written = %i)", amountWritten);
}
4

1 に答える 1

1

ああ!文書化されていませんが... NSStream インスタンスが nil になった場合、Apple はエラーを返す代わりに成功を返しますが、書き込まれたバイト数に対して 0 を返します。

私の場合、init メソッドのタイプミスは、新しくキャプチャした NSOutputStream と NSInputStream を nil で上書きしていたことを意味します。

ああ。

于 2013-06-17T15:48:07.743 に答える