我怎么能等到我使用NSStream从服务器接收到客户端的所有tcp数据包

时间:2016-02-26 00:55:25

标签: ios json tcp bonjour nsstream

 case NSStreamEvent.EndEncountered:
            BBLogMsg("End Encountered")
            guard let inputStream = self.inputStream else {
                return BBLogError("no input stream")
            }

            let bufferSize     = 4096
            var buffer         = Array<UInt8>(count: bufferSize, repeatedValue: 0)
            var message        = ""

            while inputStream.hasBytesAvailable {
                let len = inputStream.read(&buffer, maxLength: bufferSize)
                if len < 0 {
                    BBLogError("error reading stream...")
                    return self.closeStreams()
                }
                if len > 0 {
                    message += NSString(bytes: &buffer, length: len, encoding: NSUTF8StringEncoding) as! String
                }
                if len == 0 {
                    BBLogError("no more bytes available...")
                    break
                }
            }

            responseString += message
            self.resolveReseponse()

            self.closeStreams()
            break
        default:
            break
        }
public func resolveReseponse() {

    guard let data = responseString.dataUsingEncoding(NSUTF8StringEncoding) else {
        return BBLogMsg("Server get disorted data")
    }
    do {

        guard let _ = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject] else {

            return BBLogMsg("\n\n\n\nClient response string errorn\n\n\n\n\n\n")
        }

        self.didReceivedDataCallback?(responseString)
        responseString = ""
    }
    catch
    {
        BBLogMsg("JSON Error Parser Issue \(responseString)")
    }
}

我做了什么:如果服务器向客户端发送任何数据,则客户端直接验证json。如果客户端有任何损坏的json,那么客户端正在添加下一个数据包数据并进行验证。

我需要什么:客户端应该等到它获取所有数据并执行我从服务器获取的验证json数据

1 个答案:

答案 0 :(得分:0)

这不是很快,但我认为方法是一样的......

我目前正在使用这个:

if (stream == inputStream)
{
    uint8_t buffer[1024];

    int len = 0;

    NSMutableString *output = [[NSMutableString alloc] init];

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

        if (len > 0)
        {
            [output appendString: [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding]];
        }
    }
    if (output.length > 0)
    {
        [self socketValidateResponse:output];
    }
}

这是使用NSMutableString,只是附加分块数据。

-socketValidateResponse里面我有这个来验证......

- (void)socketValidateResponse:(NSString *)stringResponse
{
    stringResponse = stringResponse == nil ? @"" : stringResponse;

    id socketJson = [NSJSONSerialization JSONObjectWithData:[stringResponse dataUsingEncoding:NSUTF8StringEncoding]
                                                    options:NSJSONReadingAllowFragments
                                                      error:nil];

    BOOL isSupported = YES;

    NSLog(@"Socket Log: -> \"%@\"", stringResponse);

    if ([socketJson isKindOfClass:[NSArray class]])
    {
        NSLog(@"Response is of class NSArray");
    }
    else if ([socketJson isKindOfClass:[NSDictionary class]])
    {
        NSLog(@"Response is of class NSDictionary");
    }
    else //add more kind of class if necessary
    {
        isSupported = NO;

        NSLog(@"Response is of class %@ not supported", [stringResponse class]);
    }

    if (isSupported)
        //[self.delegate YJSocket:self didReceiveResponse:isSupported ? socketJson : nil];
}

希望这会有所帮助..干杯! :)