BSD Socket CFReadStreamRef and CFWriteStreamRef
I do have a java server. I am trying to build IPhone application that connect to the server. Also sends and receives messages. I a little confused about using CFReadStreamRef and CFWriteStreamRef. How can I pair the socket with the streams successfully. This is what i have:
fd = socket(AF_INET, SOCK_STREAM, 0);
emset(&addr, 0, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);//0;
inet_aton("192.168.1.101", &addr.sin_addr.s_addr);
CFSocketContext context = { 0, self, NULL, NULL, NULL };
listeningSocket = CFSocketCreateWithNative( NULL, fd,kCFSocketCon开发者_StackOverflow社区nectCallBack, AcceptCallback, &context);
CFDataRef connectAddr = CFDataCreate(NULL, (unsigned char *)&addr, sizeof(addr));
CFSocketConnectToAddress(self.listeningSocket, connectAddr, -1);
// As soon as i get the Connect call back into my function I try to pair the streams to the socket
CFReadStreamRef readStreamm;
CFWriteStreamRef writeStreamm;
CFStreamCreatePairWithSocket(NULL, CFSocketGetNative(listeningSocket), &readStreamm, &writeStreamm);
[readStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[readStream open];
[writeStream open];
However when i try to write or read from the stream is returning an error (-1). Another question I have if I use readStream
or writeStream
open
, and if it was successful. Is that mean that I am already connected to the server?? or do I actually have to call CFSocketConnectToAddress
. I am just trying to figure out if i need to use both the connectToAdderss and stream open. Or I should use one or the other.
Thanks in advance.
I recommend using cocoaasyncsocket. Its is a lightweight wrapper to make socket-based communication much easier. Just now I am workin on communication between iPhone and a network device. It works flawless.
[sock writeData:[@"Hello World" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:1];
Going through the implementation of cocoaasyncsocket. The socket has to be closed before opening the read/write streams. I used the CFSocketConnectToAddress
, then invalidate and release the socket. Then establish my streams. qoute:
// Invalidate and release the CFSocket - All we need from here on out is the nativeSocket
// Note: If we don't invalidate the socket (leaving the native socket open)
// then theReadStream and theWriteStream won't function properly.
// Specifically, their callbacks won't work, with the exception of kCFStreamEventOpenCompleted.
// I'm not entirely sure why this is, but I'm guessing that events on the socket fire to the CFSocket we created,
// as opposed to the CFReadStream/CFWriteStream.
CFSocketInvalidate(listeningSocket);
CFRelease(listeningSocket);
listeningSocket = NULL:
精彩评论