如题,对着网上的实例敲了一个网络代码,编译无误,运行的时候也发现发送成功了,但是为什么没有触发发送之后的回调函数呢?
以下是主体:
以下是主体:
static void UDPBonjourCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info)
{
if (data != NULL)
{
// 当socket为kCFSocketConnectCallBack时,失败时回调失败会返回一个错误代码指针,其他情况返回NULL
NSLog(@"连接失败");
return;
}
MacNetworkSys *sys_info = (MacNetworkSys *)info;
[sys_info performSelectorInBackground:@selector(ReadDeviceList) withObject:nil];
}
-(void)ReadDeviceList
{
char buffer[1024];
while (recv(CFSocketGetNative(sock_server),buffer,sizeof(buffer),0))
{
NSLog(@"设备 %@",[NSString stringWithUTF8String:buffer]);
}
}
-(void)SerachForDevices
{
CFSocketContext sockContext = {0,
self,
NULL,
NULL,
NULL};
sock_server = CFSocketCreate(kCFAllocatorDefault, // 为新对象分配内存,可以为nil
PF_INET, // 协议族,如果为0或者负数,则默认为PF_INET
SOCK_DGRAM, // 套接字类型,如果协议族为PF_INET,则它会默认为SOCK_STREAM
IPPROTO_UDP, // 套接字协议,如果协议族是PF_INET且协议是0或者负数,它会默认为IPPROTO_TCP
kCFSocketConnectCallBack, // 触发回调函数的socket消息类型,具体见Callback Types
/*(CFSocketCallBack)&*/&UDPBonjourCallBack, // 上面情况下触发的回调函数
&sockContext // 一个持有CFSocket结构信息的对象,可以为nil
);
if (sock_server != nil)
{
NSString *strAddr = ROUTER_MODE_BROADCAST_IP;
struct sockaddr_in addr4;
memset(&addr4, 0, sizeof(addr4));
addr4.sin_len = sizeof(addr4);
addr4.sin_family = AF_INET;
addr4.sin_port = htons(ROUTER_MODE_BROADCAST_PORT);
addr4.sin_addr.s_addr = inet_addr([strAddr UTF8String]);
CFDataRef address = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&addr4, sizeof(addr4));
CFSocketError err = CFSocketConnectToAddress(sock_server, address, -1);
if(err != kCFSocketSuccess)
{
NSLog(@"Socket connect failed ...");
return;
}
CFRunLoopRef cRunRef = CFRunLoopGetCurrent();
CFRunLoopSourceRef sourceRef = CFSocketCreateRunLoopSource(kCFAllocatorDefault, sock_server, 0);
if (sourceRef != nil)
{
CFRunLoopAddSource(cRunRef, sourceRef, kCFRunLoopCommonModes);
CFRelease(sourceRef);
}
else
{
NSLog(@"CFRunLoopSourceRef Error......");
}
NSString *stringToSend = @"Connecting ...";
const char *data = [stringToSend UTF8String];
int res = send(CFSocketGetNative(sock_server), data, strlen(data) + 1, 0);
if (res == -1) {
NSLog(@"Error in Sending");
}
// char *buffer = "connecting";
// send(SFSocketGetNative(sock_server), buffer, strlen(buffer), 0);
// send(CFSocketGetNative(sock_server), NULL, 0, 0);
// NSThread * backgroundThread = [[NSThread alloc] initWithTarget:self
// selector:@selector(work_thread)
// object:nil];
// [backgroundThread start];
}
}