Using NSFileHandle for server socket communication
Using NSFileHandle for server socket communication
- Subject: Using NSFileHandle for server socket communication
- From: "Mark Walker" <email@hidden>
- Date: Thu, 11 Dec 2003 18:18:36 -0700
I'm new to programming in Objective-C and Cocoa and I'm trying to
prototype a simple socket communication mechanism for an upcoming
development project.
I found the following code snippet in the book "COCOA in a Nutshell"
from O'Reilly but the sockFD returned from the [sockport socket] call
is -1 and the program throws an exception when it's run.
I've looked through the NSFileHandle and NSSocketPort documentation and
there doesn't seem to be many clues for be to grab hold of to resolve
this problem. The O'Reilly book is the only one with a simple socket
communication example that I've found so far and there doesn't seem to
be much else that I'm aware of.
If anyone can point me to a solid example of doing simple TCP socket
communications or help me understand my problem with this example I
would be very grateful.
Thanks,
mark
=============================================
-(void)startClient
{
NSLog(@"startClient called");
NSSocketPort *sockPort;
sockPort = [[NSSocketPort alloc] initRemoteWithTCPPort:12345
host:@"mark-walkers-computer"];
int sockFD = [sockPort socket];
NSLog([NSString stringWithFormat:@"sockFD:%d",sockFD]);
NSFileHandle *clientSocket;
clientSocket = [[NSFileHandle alloc] initWithFileDescriptor:sockFD];
NSNotificationCenter *nc;
nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(processServerData:)
name:NSFileHandleReadCompletionNotification
object: clientSocket];
//TODO: get data to write
NSString *dataString = [sendText stringValue];
NSLog(dataString);
NSData *dataToWrite = [dataString
dataUsingEncoding:NSASCIIStringEncoding];
[clientSocket write
Data:dataToWrite];
[clientSocket readInBackgroundAndNotify];
NSLog(@"made it to the end");
}
/*
* This method is invoked in response to
*NSFileHandleReadCompletionNotification
*/
-(void)processServerData:(NSNotification *)note
{
NSData *data = [[note userInfo]
objectForKey:NSFileHandleNotificationDataItem];
// Do something with data
[serverResponseText insertText:data];
// Tell file handle to continue waiting for data
[[note object] readInBackgroundAndNotify];
}
=============================================
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.