I have created a UDP CFSocket and I'm able to send data without using any file handles. But, when I create CFReadStreamRef, CFWriteStreamRef and use them to send data, it fails. The control does not return. Can anyone help me regarding this? The code is as below:
-(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);
}
}
}
I was working on a UDP socket some time back. The problem in your code is that you are not connecting the server before you can use the the socket.
The code which I wrote some time back is below. Hope it helps
}