Hi experts.
I created a socket server and when the server accept a connection, I associate the CFSocketNativeHandle with NSInputStream and NSOutputStream.
I implement method - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode.
I think the connection is closed by the client, if I received event NSStreamEventHasBytesAvailable and the length of data i read is 0.
like the following codes:
is it right ? if not, how do I know the connection is closed by the client?
thanks.
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
switch (eventCode)
{
case NSStreamEventOpenCompleted:
break;
case NSStreamEventHasBytesAvailable:
{
NSMutableData *data = [NSMutableData data];
uint8_t buffer[1024];
NSInputStream *inputStream = (NSInputStream *)aStream;
while (inputStream.hasBytesAvailable)
{
NSInteger readSize = [inputStream read:buffer maxLength:kBufferSize];
if (readSize > 0)
{
[data appendBytes:buffer length:readSize];
} else if (-1 == readSize)
{
NSError *error = aStream.streamError;
if (error)
{
// ...
}
}
}
if(0 == data.length)
{// the connection is closed by the client
}
}
break;
// ...
default:
break;
}
}