Working with Streams

Working with Streams  

本章讨论了如何创建,打开,并就读取错误检查和写入流。它还介绍了如何读取读取流,如何写入一个写入流,如何防止阻塞时读取或写入一个流,并通过代理服务器如何导航流。

Working with Read Streams

我们从为一个文件创建可读流开始,列表2-1,所示。

Listing 2-1  Creating a read stream from a file

CFReadStreamRef myReadStream = CFReadStreamCreateWithFile(kCFAllocatorDefault, fileURL);
在这个清单中,kCFAllocatorDefault参数指定当前的默认系统分配器用来分配流和fileURL参数存储指定的本读流正在创建的文件,如文件,名称: file:///Users/joeuser/Downloads/MyApp.sit.

isting 2-2  Opening a read stream

if (!CFReadStreamOpen(myReadStream)) {
    CFStreamError myErr = CFReadStreamGetError(myReadStream);
    // An error has occurred.
        if (myErr.domain == kCFStreamErrorDomainPOSIX) {
        // Interpret myErr.error as a UNIX errno.
        } else if (myErr.domain == kCFStreamErrorDomainMacOSStatus) {
        // Interpret myErr.error as a MacOS error code.
            OSStatus macError = (OSStatus)myErr.error;
        // Check other error domains.
    }
}
该CFReadStreamOpen函数返回TRUE和FALSE来指示成功失败如果打开过程中遇到错误。如果CFReadStreamOpen返回FALSE,该示例调用CFReadStreamGetError函数,它返回一个类型的两个值组成CFStreamError结构:( a domain code and an error code) 域代码和错误代码。该域名代码表明该错误代码应该如何解释。例如,如果域代码kCFStreamErrorDomainPOSIX,错误代码是一个UNIX errno的值。其他错误域kCFStreamErrorDomainMacOSStatus,这表明该错误代码是OSStatus价值MacErrors.h界定,kCFStreamErrorDomainHTTP,这表明该错误代码是由CFStreamErrorHTTP定义的枚举值之一。

Working with Write Streams

Listing 2-5  Creating, opening, writing to, and releasing a write stream

CFWriteStreamRef myWriteStream =
        CFWriteStreamCreateWithFile(kCFAllocatorDefault, fileURL);
if (!CFWriteStreamOpen(myWriteStream)) {
    CFStreamError myErr = CFWriteStreamGetError(myWriteStream);
    // An error has occurred.
    if (myErr.domain == kCFStreamErrorDomainPOSIX) {
    // Interpret myErr.error as a UNIX errno.
    } else if (myErr.domain == kCFStreamErrorDomainMacOSStatus) {
        // Interpret myErr.error as a MacOS error code.
        OSStatus macError = (OSStatus)myErr.error;
        // Check other error domains.
    }
}
UInt8 buf[] = "Hello, world";
UInt32 bufLen = strlen(buf);
 
while (!done) {
    CFTypeRef bytesWritten = CFWriteStreamWrite(myWriteStream, buf, strlen(buf));
    if (bytesWritten < 0) {
        CFStreamError error = CFWriteStreamGetError(myWriteStream);
        reportError(error);
    } else if (bytesWritten == 0) {
        if (CFWriteStreamGetStatus(myWriteStream) == kCFStreamStatusAtEnd) {
            done = TRUE;
        }
    } else if (bytesWritten != strlen(buf)) {
        // Determine how much has been written and adjust the buffer
        bufLen = bufLen - bytesWritten;
        memmove(buf, buf + bytesWritten, bufLen);
 
        // Figure out what went wrong with the write stream
        CFStreamError error = CFWriteStreamGetError(myWriteStream);
        reportError(error);
 
    }
}
CFWriteStreamClose(myWriteStream);
CFRelease(myWriteStream);
myWriteStream = NULL;

Preventing Blocking When Working with Streams

Using Polling to Prevent Blocking

为了调查的读或写数据流,你需要看看流准备好了没有。 当要发送可写流的时候,可以通过调用函数CFWriteStreamCanAcceptBytes。 如果它返回TRUE,那么你可以使用CFWriteStreamWrite函数,因为它会立即能写而不会阻塞。 同样,对于一个读数据流,然后再调用CFReadStreamRead,调用函数CFReadStreamHasBytesAvailable。 通过轮询流状态,可避免阻塞的等待流的线程就绪。

Listing 2-6  Polling a read stream

while (!done) {
    if (CFReadStreamHasBytesAvailable(myReadStream)) {
        UInt8 buf[BUFSIZE];
        CFIndex bytesRead = CFReadStreamRead(myReadStream, buf, BUFSIZE);
        if (bytesRead < 0) {
            CFStreamError error = CFReadStreamGetError(myReadStream);
            reportError(error);
        } else if (bytesRead == 0) {
            if (CFReadStreamGetStatus(myReadStream) == kCFStreamStatusAtEnd) {
                done = TRUE;
            }
        } else {
            handleBytes(buf, bytesRead);
        }
    } else {
        // ...do something else while you wait...
    }
}

Listing 2-7 is a polling example for a write stream.

Listing 2-7  Polling a write stream

UInt8 buf[] = "Hello, world";
UInt32 bufLen = strlen(buf);
 
while (!done) {
    if (CFWriteStreamCanAcceptBytes(myWriteStream)) {
        int bytesWritten = CFWriteStreamWrite(myWriteStream, buf, strlen(buf));
        if (bytesWritten < 0) {
            CFStreamError error = CFWriteStreamGetError(myWriteStream);
            reportError(error);
        } else if (bytesWritten == 0) {
            if (CFWriteStreamGetStatus(myWriteStream) == kCFStreamStatusAtEnd)
            {
                done = TRUE;
            }
        } else if (bytesWritten != strlen(buf)) {
            // Determine how much has been written and adjust the buffer
            bufLen = bufLen - bytesWritten;
            memmove(buf, buf + bytesWritten, bufLen);
 
            // Figure out what went wrong with the write stream
            CFStreamError error = CFWriteStreamGetError(myWriteStream);
            reportError(error);
        }
    } else {
        // ...do something else while you wait...
    }
}

Using a Run Loop to Prevent Blocking

The run loop是一种监视特别事件发生的线程。当run loop监视的事件发生时,它将会调用事先定义好的回调函数进行通知。

This example begins by creating a socket read stream:

CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host, port,
                                   &myReadStream, NULL);
where the CFHost object reference, host, specifies the remote host with which the read stream is to be made and the port parameter specifies the port number that the host uses. The CFStreamCreatePairWithSocketToCFHostfunction returns the new read stream reference in myReadStream. The last parameter, NULL, indicates that the caller does not want to create a write stream. If you wanted to create a write steam, the last parameter would be, for example, &myWriteStream.

efore opening the socket read stream, create a context that will be used when you register to receive stream-related events:

CFStreamClientContext myContext = {0, myPtr, myRetain, myRelease, myCopyDesc};
0是版本号,myptr是要传递给回调函数的参数指针,使用myRetain方法保存myptr,使用完成后使用myRelease方法释放myptr;  Finally,copyDescription is a parameter to a function to provide a description of the stream. For example, if you were to call CFCopyDesc(myReadStream) with the stream client context shown above, CFStream would callmyCopyDesc(myPtr).

The client context also allows you the option of setting the retainrelease, and copyDescription parameters toNULL. If you set the retain and release parameters to NULL, then the system will expect you to keep the memory pointed to by the info pointer alive until the stream itself is destroyed. If you set the copyDescription parameter to NULL, then the system will provide, if requested, a rudimentary description of what is in the memory pointed to by the info pointer.

With the client context set up, call the function CFReadStreamSetClient to register to receive stream-related events. CFReadStreamSetClient requires that you specify the callback function and the events you want to receive. The following example in Listing 2-8 specifies that the callback function wants to receive thekCFStreamEventHasBytesAvailablekCFStreamEventErrorOccurred, and kCFStreamEventEndEncounteredevents. Then schedule the stream on a run loop with the CFReadStreamScheduleWithRunLoop function. SeeListing 2-8 for an example of how to do this.

Listing 2-8  Scheduling a stream on a run loop

CFOptionFlags registeredEvents = kCFStreamEventHasBytesAvailable |
        kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
if (CFReadStreamSetClient(myReadStream, registeredEvents, myCallBack, &myContext)
{
    CFReadStreamScheduleWithRunLoop(myReadStream, CFRunLoopGetCurrent(),
                                    kCFRunLoopCommonModes);
}

With the stream scheduled on the run loop, you are ready to open the stream as shown in Listing 2-9.

Listing 2-9  Opening a nonblocking read stream

if (!CFReadStreamOpen(myReadStream)) {
    CFStreamError myErr = CFReadStreamGetError(myReadStream);
    if (myErr.error != 0) {
    // An error has occurred.
        if (myErr.domain == kCFStreamErrorDomainPOSIX) {
        // Interpret myErr.error as a UNIX errno.
            strerror(myErr.error);
        } else if (myErr.domain == kCFStreamErrorDomainMacOSStatus) {
            OSStatus macError = (OSStatus)myErr.error;
            }
        // Check other domains.
    } else
        // start the run loop
        CFRunLoopRun();
}
 

Now, wait for your callback function to be executed. In your callback function, check the event code and take appropriate action. See Listing 2-10.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值