CFSocketSendData 不会发送数据?
我是 Objective C 网络的新手。我为一个简单的 WOL 应用程序编写了以下代码。我可以成功创建一个套接字,然后设置一个地址(我只能设置本地计算机地址,但这是另一个问题)。 但是,当尝试使用 CFSocketSendData 发送数据时,它不会发送数据(显示数据未发送消息)。 我是否正确使用 CFSocketSendData,还是其他地方有问题?
任何帮助将不胜感激,谢谢。
struct sockaddr_in 地址;
memset(&addr, 0, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT); //port
inet_aton(IP, &addr.sin_addr);//IP is the network IP of the machine e.g 192.168.0.2
NSData *address = [NSData dataWithBytes: &addr length: sizeof(addr)];
if (CFSocketSetAddress(WOLsocket, (CFDataRef)address) != kCFSocketSuccess){
NSLog(@"Address could not be set!");
}
else{
NSLog(@"Address set");
char ethadd []= "helloworld";
CFDataRef Data = CFDataCreate(NULL, (const UInt8*)ethadd, sizeof(ethadd));
if (CFSocketSendData(WOLsocket, NULL, Data, 0) < 0){
NSLog(@"Data could not be sent!");
}
else NSLog(@"Data Sent");
}
I am a newbie to objective C networking. I have put together the code below for a simple WOL application. I can successfully create a socket, and then set an address (I only am able to set the local machine address but thats another question).
However when trying to send the data using CFSocketSendData, it does not send the data(Data not sent message displayed).
Am I using CFSocketSendData correctly, or is there a problem elsewhere?
Any help will be greatly appreciated, thanks.
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT); //port
inet_aton(IP, &addr.sin_addr);//IP is the network IP of the machine e.g 192.168.0.2
NSData *address = [NSData dataWithBytes: &addr length: sizeof(addr)];
if (CFSocketSetAddress(WOLsocket, (CFDataRef)address) != kCFSocketSuccess){
NSLog(@"Address could not be set!");
}
else{
NSLog(@"Address set");
char ethadd []= "helloworld";
CFDataRef Data = CFDataCreate(NULL, (const UInt8*)ethadd, sizeof(ethadd));
if (CFSocketSendData(WOLsocket, NULL, Data, 0) < 0){
NSLog(@"Data could not be sent!");
}
else NSLog(@"Data Sent");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有在代码片段中包含
CFSocketCreate(...)
代码,但我假设您选择了默认值、PF_INET 系列和 TCP 协议。对于TCP协议来说,仅仅设置地址是不够的,还需要建立一个
连接到您的目标端点。
首先调用函数...
CFSocketConnectToAddress (WOLsocket, address, 10.0);
然后发送数据...
CFSocketSendData(WOLsocket, NULL, Data, 0)
You didn't include the
CFSocketCreate(...)
code in your snippet, but I assume that you chose the defaults, the PF_INET family and the TCP protocol.With the TCP protocol, setting the address is not enough, you need to establish a
connection to your destination endpoint.
First call the function...
CFSocketConnectToAddress (WOLsocket, address, 10.0);
then send your data...
CFSocketSendData(WOLsocket, NULL, Data, 0)