BSD套接字CFReadStreamRef和CFWriteStreamRef

时间:2010-11-27 02:54:23

标签: iphone objective-c cocoa-touch sockets

我有一个java服务器。我正在尝试构建连接到服务器的IPhone应用程序。还发送和接收消息。我对使用CFReadStreamRef和CFWriteStreamRef有点困惑。如何成功地将套接字与流配对。这就是我所拥有的:

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,kCFSocketConnectCallBack, 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];

然而,当我尝试从流中写入或读取时返回错误(-1)。如果我使用readStreamwriteStream open,如果成功,我会遇到另一个问题。这是否意味着我已经连接到服务器?或者我实际上是否必须致电CFSocketConnectToAddress。我只想弄清楚我是否需​​要同时使用connectToAdders和流打开。或者我应该使用其中一个。

提前致谢。

2 个答案:

答案 0 :(得分:0)

我建议使用cocoaasyncsocket。它是一个轻量级的包装器,使基于插槽的通信变得更加容易。刚才我正在研究iPhone和网络设备之间的通信。它完美无缺。

[sock writeData:[@"Hello World" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:1];

答案 1 :(得分:0)

完成cocoaasyncsocket的实现。在打开读/写流之前必须关闭套接字。我使用了CFSocketConnectToAddress,然后使套接字无效并释放。然后建立我的流。 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: