gpt4 book ai didi

iOS NSStream 套接字读取 TCP 不稳定和截断

转载 作者:行者123 更新时间:2023-11-29 03:08:24 24 4
gpt4 key购买 nike

我正在使用以下代码从服务器套接字读取数据。一切开始都很好,但随着事情的进展,返回的数据被截断并错误地分块。我已经阅读了所有尝试不同的东西,比如改变缓冲区大小和同步代码,但仍然没有运气。一开始我以为是到期了

-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

被异步调用,所以我尝试同步它,但运气不好。我多次增加了缓冲区,但没有运气...我只想在每次触发它时从服务器读取一整行传递给 messagedReceived 。我确信我正在做一些愚蠢的事情或者忽略了一些对某些人来说显而易见的事情。

-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

switch (streamEvent) {

case NSStreamEventOpenCompleted:
DLog(@"Connection Opened!!!");
[delegate connectionOpened];
break;

case NSStreamEventHasBytesAvailable:

if (theStream == inputStream) {



uint8_t buffer[1024];
int len = 0;

while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];

if (len > 0) {

NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

if (nil != output) {
DLog(@"%@", output);
[self messageReceived:output];

}
}
}
}




break;

case NSStreamEventErrorOccurred:
DLog(@"Can not connect to the host!");

最佳答案

我最终所做的只是自己搜索行尾字符并对其进行构建处理。

-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

switch (streamEvent) {

case NSStreamEventOpenCompleted:
DLog(@"Connection Opened!!!");
[delegate connectionOpened];
break;

case NSStreamEventHasBytesAvailable:

if (theStream == inputStream) {



uint8_t buffer[1024];
int len = 0;

while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];

if (len > 0) {

NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

if (nil != output) {
if ([output rangeOfString:@"\n"].location == NSNotFound) {

line = AS(line, output);

} else {



NSArray *chunks = [output componentsSeparatedByString: @"\n"];

line = AS(line, chunks[0]);
[self messageReceived:line];
DLog("M: %@", line);

line = chunks[1];


}



}
}
}
}

关于iOS NSStream 套接字读取 TCP 不稳定和截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22514448/

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