要从文件或socket中读取数据,需要打开文件或socket,并创建一个 DISPATCH_SOURCE_TYPE_READ 类型的dispatch source。你指定的事件处理器必须能够读取和处理描述符中的内容。对于文件,需要读取文件数据,并为应用创建适当的数据结构;对于网络socket,需要处理最新接收到的网络数据。
读取数据时,你总是应该配置描述符使用非阻塞操作,虽然你可以使用 dispatch_source_get_data 函数查看当前有多少数据可读,但在你调用它和实际读取数据之间,可用的数据数量可能会发生变化。如果底层文件被截断,或发生网络错误,从描述符中读取会阻塞当前线程,停止在事件处理器中间并阻止dispatch queue去执行其它任务。对于串行queue,这样还可能会死锁,即使是并发queue,也会减少queue能够执行的任务数量。
下面例子配置dispatch source从文件中读取数据,事件处理器读取指定文件的全部内容到缓冲区,并调用一个自定义函数来处理这些数据。调用方可以使用返回的dispatch source在读取操作完成之后,来取消这个事件。为了确保dispatch queue不会阻塞,这里使用了fcntl函数,配置文件描述符执行非阻塞操作。dispatch source安装了取消处理器,确保最后关闭了文件描述符。
在这个例子中,自定义的 MyProcessFileData 函数确定读取到足够的数据,返回YES告诉dispatch source读取已经完成,可以取消任务。通常读取描述符的dispatch source在还有数据可读时,会重复调度事件处理器。如果socket连接关闭或到达文件末尾,dispatch source自动停止调度事件处理器。如果你自己确定不再需要dispatch source,也可以手动取消它。
BOOL myProcesFileData(char *buffer, size_t actutalSize, int fd){
NSString *result2 = [[NSString alloc]initWithBytes:buffer length:actutalSize encoding:4];
NSLog(@"%@", result2);
//出来后,我想从文件里扔掉已读部分,有可能在你清空文件时,又有新的写入到文件,所以保证读、写加锁或使用串行队列
/* 清空文件 */
ftruncate(fd,0);
/* 重新设置文件偏移量 */
lseek(fd,0,SEEK_SET);
return NO;
}
void cancelHandler(void *context){
int fd = (int)dispatch_source_get_handle((__bridge dispatch_source_t _Nonnull)(context));
close(fd);
}
dispatch_source_t createFileDispatchSource(const char *fileName){
//1:打开文件,获取文件描述符(open成功则返回文件描述符,否则返回-1)
int fd = open(fileName, O_RDWR);
if (fd == -1) {
return NULL;
}
//2:设置文件操作为非堵塞模式(也可以在pen函数中设置:open(fileName, O_RDONLY|O_NONBLOCK))
fcntl(fd, F_SETFL, O_NONBLOCK);
//3:创建派发源
dispatch_queue_t queue = dispatch_queue_create("同一文件操作都在串行队列中", DISPATCH_QUEUE_SERIAL);
dispatch_source_t fdDispatchSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fd, 0, queue);
if (fdDispatchSource == NULL) {
close(fd);
return NULL;
}
//4:设置”文件可读“事件响应处理器
dispatch_source_set_event_handler(fdDispatchSource, ^{
size_t estimated = dispatch_source_get_data(fdDispatchSource);
char *buffer = (char*)malloc(estimated);
if(buffer){
size_t actualSize = read(fd, buffer, estimated);
BOOL done = myProcesFileData(buffer, actualSize, fd);
free(buffer);
if (done) {
dispatch_source_cancel(fdDispatchSource);
}
}
});
//5:设置取消处理器
/*使用block处理器
dispatch_source_set_cancel_handler(fdDispatchSource, ^{
close(fd);
NSLog(@"文件派发源已被取消");
});
*/
//使用函数处理器
dispatch_set_context(fdDispatchSource, (__bridge void *)fdDispatchSource);
dispatch_source_set_cancel_handler_f(fdDispatchSource, cancelHandler);
//6:启动事件源
dispatch_resume(fdDispatchSource);
return fdDispatchSource;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"==========描述符派发源===========");
dispatch_source_t fdDispatchSource = createFileDispatchSource("/Users/feinno/Desktop/test");
[[NSRunLoop currentRunLoop]run];
}
return 0;
}