我已经创建了一个 UDP CFSocket,我可以在不使用任何文件句柄的情况下发送数据。但是,当我创建 CFReadStreamRef、CFWriteStreamRef 并使用它们发送数据时,它会失败。控件不返回。任何人都可以帮我解决这个问题吗?代码如下:
-(void) CFSocketType2
{
CFSocketRef s = CFSocketCreate(kCFAllocatorDefault, PF_INET,
SOCK_DGRAM , IPPROTO_UDP,
0,
NULL,
NULL);
struct sockaddr_in sin;
struct hostent *host;
host = gethostbyname("localhost");
memset(&sin, 0, sizeof(sin));
memcpy(&(sin.sin_addr), host->h_addr,host->h_length);
sin.sin_family = AF_INET;
sin.sin_port = htons(5527);
CFDataRef address, data;
UInt8 message[] = "Hello world 123";
address = CFDataCreate(NULL, (UInt8 *)&sin, sizeof(sin));
data = CFDataCreate(NULL, message, sizeof(message));
//Sending data without using file handles
CFSocketConnectToAddress(s, address, 0);
CFSocketSendData(s, NULL, data, 0);
// The problem starts here
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
CFStreamCreatePairWithSocket(kCFAllocatorDefault, CFSocketGetNative(s), &readStream, &writeStream);
if (readStream && writeStream)
{
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
if (! CFReadStreamOpen(readStream) || ! CFWriteStreamOpen(writeStream))
{
NSLog(@"Could not initialize streams!");
}
else
{
UInt8 msg [] ="Hello World";
CFIndex a = CFWriteStreamWrite(writeStream, msg, sizeof(msg));
NSLog(@"Return value is %d", a);
}
}
}