我想在 IOS 中使用 UDP 广播进行网络发现。我不知道该怎么做。你能给我一些建议吗?
我想这样做tutorial .
最佳答案
你可以使用 Cocoa 异步套接字
https://github.com/robbiehanson/CocoaAsyncSocket
下面是代码
GCDAsyncUdpSocket *udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![udpSocket enableReusePort:YES error:&error])
{
return;
}
if (![udpSocket bindToPort:8888 error:&error])
{
return;
}
if (![udpSocket beginReceiving:&error])
{
return;
}
error = nil;
if(![udpSocket enableBroadcast:YES error:&error])
{
}
NSData *data = [@"DISCOVER_FUIFSERVER_REQUEST" dataUsingEncoding:NSUTF8StringEncoding];
[udpSocket sendData:data toHost:@“255.255.255.255” port:8888 withTimeout:10 tag:100];
下面是您将获得响应的委托(delegate)方法
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *msg1 = [NSString stringWithFormat:@"RECV: %@ FROM: %@", msg,[GCDAsyncUdpSocket hostFromAddress:address]];
if([msg isEqualToString:@"DISCOVER_FUIFSERVER_RESPONSE"])
{
}
}
如果在 udp 套接字连接时出现错误,将调用此委托(delegate)方法
- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error
{
if (error) {
NSString *msg = [NSString stringWithFormat:@"RECV: error: %@", [error localizedDescription]];
}
}
关于ios - 如何在 IOS 中使用 UDP 广播进行网络发现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46926815/