2 * Extension for NSFileHandle to make it capable of easy network programming
4 * Version 1.0, get the newest from http://michael.stapelberg.de/NSFileHandleExt.php
6 * Copyright 2007 Michael Stapelberg
8 * Distributed under BSD-License, see http://michael.stapelberg.de/BSD.php
13 #define CONN_TIMEOUT 5
14 #define BUFFER_SIZE 256
16 @implementation NSFileHandle(NSFileHandleExt)
18 -(NSString*)readLine {
19 // If the socket is closed, return an empty string
20 if ([self fileDescriptor] <= 0)
23 int fd = [self fileDescriptor];
25 // Allocate BUFFER_SIZE bytes to store the line
26 int bufferSize = BUFFER_SIZE;
27 char *buffer = (char*)malloc(bufferSize + 1);
29 [[NSException exceptionWithName:@"No memory left" reason:@"No more memory for allocating buffer" userInfo:nil] raise];
31 int bytesReceived = 0, n = 1;
34 n = read(fd, buffer + bytesReceived++, 1);
37 [[NSException exceptionWithName:@"Socket error" reason:@"Remote host closed connection" userInfo:nil] raise];
39 if (bytesReceived >= bufferSize) {
41 bufferSize += BUFFER_SIZE;
42 buffer = (char*)realloc(buffer, bufferSize + 1);
44 [[NSException exceptionWithName:@"No memory left" reason:@"No more memory for allocating buffer" userInfo:nil] raise];
47 switch (*(buffer + bytesReceived - 1)) {
49 buffer[bytesReceived-1] = '\0';
50 NSString* s = [NSString stringWithCString: buffer encoding: NSUTF8StringEncoding];
52 s = [NSString stringWithCString: buffer encoding: NSISOLatin1StringEncoding];
59 buffer[bytesReceived-1] = '\0';
60 NSString *retVal = [NSString stringWithCString: buffer encoding: NSUTF8StringEncoding];
61 if ([retVal length] == 0)
62 retVal = [NSString stringWithCString: buffer encoding: NSISOLatin1StringEncoding];