I want to receive data by specifying the length of the data in socket communication using NSSstream.

Asked 1 years ago, Updated 1 years ago, 133 views

I used a library called GCDAsyncSocket for socket communication.
Debugging with IPv6 only Network

lost connect Error Domain=NSPOSIXErrorDomain Code=51 "Network is unreachable" UserInfo={NSLocalizedDescription=Network is unreachable, NSLocalizedFailureReason=Error in connect() function}


because the error
came out and I couldn't help it. We are implementing it in NSSstream, but we would like you to inform us that we cannot deal with the situation where there is a lack of data due to receiving data.

With GCDAsyncSocket, I was able to read sockets of the length specified by readDataToLength, and I was able to figure out the size of the sockets to be received, but is it possible for NSSstream to implement them like that?

NSSstreamEventHasBytesAvailable retrieves NSData as follows:

uint8_t buffer [4096];
unsigned intlen=0;
while (InputStream hasBytesAvailable)
{
    InputStream getBuffer: & buffer length: &len;
    len = [InputStream read: buffer maxLength: size of (buffer)];
    if(len>0){

        NSData*data=[NSDataDataWithBytes:buffer length:len];

    }
}

Thank you for your cooperation.

ios objective-c socket

2022-09-30 21:13

1 Answers

I think the second and fifth lines are wrong.
First, you don't need the fifth line, so suddenly

-(NSUInteger) read:(nonnulluint8_t*) buffer maxLength:(NSUInteger) length;

Read the data using the method.At that time, I gave Len's pointer, so I think the reason is that he is trying to read up to the ridiculously large number of bytes that are Len's address.
Below is a code that reads one byte at a time until a separator character arrives.

uint8_toneByte;
NSInteger actuallyRead = 0;
BOOL repeat = YES;
do {//read from stream
    actuallyRead = [readStream read: & oneByte maxLength:1U];
        // check data
    switch(actuallyRead){
        case1://success normal one byte.
            if(oneByte=='\0')
                repeat = NO;
            else
                CFDataAppendBytes (recievedData, & oneByte, activeRead);
            break;
        case0:
            return;
            break;
        default:
            NSLog(@"Error at reading stream%@:%@", NSSstringFromSelector(_cmd), [selfclass]);
            NSLog(@"StreamStatus:%lu", [readStreamStreamStatus]);
            NSLog(@"StreamError: %@", [readStreamstreamError]);
            return;
            break;
    }// end switch
} while(repeat);


2022-09-30 21:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.