gpt4 book ai didi

iphone - 流式获取数据 - NSInputStream

转载 作者:太空狗 更新时间:2023-10-30 03:46:30 28 4
gpt4 key购买 nike

全部,

我有一台服务器,它有一个用于通信的 TCP 套接字流。我需要访问该流并读取它需要发送给我的初始数据。

我目前的代码如下。老实说,我对此完全视而不见。我不确定这是否正确,更不用说适合这项工作了。

-(void) initNetworkCommunication
{
//input stream
NSInputStream *iStream;
NSURL *url = [url initWithString:@"192.168.17.1:2004"];

[iStream initWithURL:url];
[iStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[iStream open];

}

所以从我的角度来看,这段代码初始化了流,但是我如何从流中读取数据呢?

谢谢

最佳答案

有两种方法可以从流中获取数据:轮询和使用流事件。

轮询更简单,但会阻塞运行它的线程。如果使用此方法,则无需执行 setDelegate:scheduleInRunLoop:forMode:调用。通过重复调用 read:maxLength: 执行轮询。

NSInteger result;
uint8_t buffer[BUFFER_LEN]; // BUFFER_LEN can be any positive integer
while((result = [iStream read:buffer maxLength:BUFFER_LEN]) != 0) {
if(result > 0) {
// buffer contains result bytes of data to be handled
} else {
// The stream had an error. You can get an NSError object using [iStream streamError]
}
}
// Either the stream ran out of data or there was an error

使用流事件需要设置委托(delegate)并将流添加到运行循环中。流不会阻塞线程,而是会在某些事件发生时(包括接收数据时)向其委托(delegate)发送一条 stream:handleEvent: 消息。然后委托(delegate)可以从流中检索数据。这是一个示例 stream:handleEvent: 方法:

- (void)stream:(NSInputStream *)iStream handleEvent:(NSStreamEvent)event {
BOOL shouldClose = NO;
switch(event) {
case NSStreamEventEndEncountered:
shouldClose = YES;
// If all data hasn't been read, fall through to the "has bytes" event
if(![iStream hasBytesAvailable]) break;
case NSStreamEventHasBytesAvailable: ; // We need a semicolon here before we can declare local variables
uint8_t *buffer;
NSUInteger length;
BOOL freeBuffer = NO;
// The stream has data. Try to get its internal buffer instead of creating one
if(![iStream getBuffer:&buffer length:&length]) {
// The stream couldn't provide its internal buffer. We have to make one ourselves
buffer = malloc(BUFFER_LEN * sizeof(uint8_t));
freeBuffer = YES;
NSInteger result = [iStream read:buffer maxLength:BUFFER_LEN];
if(result < 0) {
// error copying to buffer
break;
}
length = result;
}
// length bytes of data in buffer
if(freeBuffer) free(buffer);
break;
case NSStreamEventErrorOccurred:
// some other error
shouldClose = YES;
break;
}
if(shouldClose) [iStream close];
}

关于iphone - 流式获取数据 - NSInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6685785/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com