UDPソケットを作成してブロードキャストポートにデータを送信しようとしているため、同じWiFiネットワーク上の他のデバイスで受信できます。私は受け入れられた答えhereで与えられた放送ポートのIPアドレスを計算しています。その後、私は以下の通りであるいくつかの接続コード書かれているGCDAsyncUDPSocket:正常に送信されたにもかかわらずデータを受信していません
:
self.udpSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue() socketQueue:nil];
NSError *error;
[self.udpSocket enableReusePort:YES error:&error];
[self.udpSocket enableBroadcast:YES error:&error];
- (IBAction)sendMessageToBroadcastPort:(id)sender {
[self.udpSocket sendData:[@"Hi" dataUsingEncoding:NSUTF8StringEncoding] toHost:[self getUDPBroadcastAddress] port:5556 withTimeout:-1 tag:1];
}
を私は、デリゲートメソッドdidSendDataとしてデータを送信で成功を得る:呼び出されます。
私はここで何が欠けているのか教えてください。
ありがとうございます!
UPDATE:放送ポートからのデータを受信するための Cpde:
- (void)listenForPackets
{
dispatch_queue_t dQueue = dispatch_queue_create("client udp socket", NULL);
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dQueue socketQueue:nil];
NSError *error = nil;
if (![udpSocket bindToPort:5556 error:&error]) {
NSLog(@"Error binding: %@",error);//not connecting to host
return;
}
if (![udpSocket beginReceiving:&error]) {
NSLog(@"Error receiving: %@",error);
return;
}
NSLog(@"Socket Ready");
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (msg)
{
NSLog(@"RCV: %@", msg);
}
else
{
NSString *host = nil;
uint16_t port = 0;
[GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
NSLog(@"Unknown message from : %@:%hu", host, port);
}
}
私は計算後の取得放送IPは192.168.2.255
UPDATE 2::
私が直面しているシナリオは本当に違って変わっています。受信はときどき動作し、時には受信しません。 2つのアプリケーションをインストールしたときに、データが受信されませんでした。送信のみが成功しました。私はアプリをデータの受信を開始した後も続けた。いくつかの例では、しばらくして受信を停止したり、問題なく受信を続けました。何が問題なの?
UDPは接続が少ないので、 'connectToHost'を呼び出す必要はありません。あなたは 'sendData:toHost:port:withTimeout'を使用するべきです – Paulw11