简体   繁体   中英

client side on MAC OS X gets empty responses (using BSD sockets and Cocoa's NSFileHandle)

I'm connecting a linux machine (acting as server) and a Mac machine (as the client) using bsd sockets. Because of Cocoa's improve I'm setting bsd sockets the usual way but then encapsulating it on a NSFileHandle object. I'm using this object to send and receive messages from the server.

The protocol goes as follow: Linux gets a message from the Mac, and immediately echoes that message back to Mac.

Everything goes well 'till I get the message back. My mac gets the message empty.

Here is what I do, when sending the message.

const char *toSend = [line cStringUsingEncoding:NSASCIIStringEncoding];
printf("message to send %s\n", toSend);
//[self writeData:[line dataUsingEncoding: encoding]];

[self writeData:[NSData dataWithBytes:toSend length:strlen(toSend)]];
[self readInBackgroundAndNotify];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:observer selector:@selector(process:) name:NSFileHandleReadCompletionNotification object:self];

As you can see I set "process" on "observer" to process the server respond. this method does the following.

NSFileHandle *fh = [notification object];
NSData *data = [fh availableData];
NSString *dataString = [[NSString alloc]
                        initWithData:data
                        encoding:NSASCIIStringEncoding];

printf("server says %s\n", [dataString cStringUsingEncoding:NSASCIIStringEncoding]);    
[dataString release];

On console I get: "server says " and that's all

On the Linux side I'm printing what I get, and before sending it back I check I there's something.

I know I can use bsd regular sockets on Mac but I really want to pull this of.

Shouldn't you add the observer before calling readInBackgroundAndNotify? Your message could be read and gone by the time your process gets around to doing that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM