I had a problem developing a tcp / client server in a c object with Bonjour.
On the server side, I open threads correctly, and I use the handleEvent function to send and receive data. But I do not know how to send and receive data correctly. I read this great post: The correct way to send data through a socket with NSOutputStream So I use a queued system to send data:
switch(eventCode) { case NSStreamEventOpenCompleted: { NSLog(@"Complete"); } break; case NSStreamEventHasSpaceAvailable: { if (stream == _outputStream) [self _sendData]; } break;
...
- (void)_sendData { flag_canSendDirectly = NO; NSData *data = [_dataWriteQueue lastObject]; if (data == nil) { flag_canSendDirectly = YES; return; } uint8_t *readBytes = (uint8_t *)[data bytes]; readBytes += currentDataOffset; NSUInteger dataLength = [data length]; NSUInteger lengthOfDataToWrite = (dataLength - currentDataOffset >= 1024) ? 1024 : (dataLength - currentDataOffset); NSInteger bytesWritten = [_outputStream write:readBytes maxLength:lengthOfDataToWrite]; currentDataOffset += bytesWritten; if (bytesWritten > 0) { self.currentDataOffset += bytesWritten; if (self.currentDataOffset == dataLength) { [self.dataWriteQueue removeLastObject]; self.currentDataOffset = 0; } }
}
. So basically I just send individual data across many packets. But I do not see how to recover data on the client side. And I think I misunderstood the NSStreamEventHasBytesAvailable event. Because here I send a lot of packets, but this client-side event fires only once. And when I restore the data from the buffer, the data seems corrupted. I would really appreciate if someone could clarify all this, the documentation is actually not entirely clear (or maybe I missed the point ...).
case NSStreamEventHasBytesAvailable: { if (stream == _inputStream) { //read data uint8_t buffer[1024]; int len; while ([_inputStream hasBytesAvailable]) { len = [_inputStream read:buffer maxLength:sizeof(buffer)]; if (len > 0) { NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding]; //NSData *theData = [[NSData alloc] initWithBytes:buffer length:len]; UnitySendMessage("AppleBonjour_UnityNetworkManager(Clone)", "OnLocalClientReceiveMessageFromServer", [output cStringUsingEncoding:NSUTF8StringEncoding]); } } }
ios objective-c sockets tcp nsstream
thegrandwaazoo
source share