连接到广播而不是服务器后,AsyncUdpSocket接收数据的小问题 [英] Little problem with AsyncUdpSocket receiving data after connecting to broadcast instead of server

查看:123
本文介绍了连接到广播而不是服务器后,AsyncUdpSocket接收数据的小问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的AsyncUdpSocket出现问题。

I have a problem with AsyncUdpSocket.

我曾经连接到服务器,发送一些数据并获得一些响应。现在,由于我不知道服务器的实际地址,我不得不更改代码并将数据发送到广播地址255.255.255.255。

I used to connect to a server, send some data and get some response. Now since I do not know the actual address of the server I had to change my code and send the data to the broadcast address 255.255.255.255.

这是我的代码:

NSString *bchost = @"255.255.255.255";
NSString *host = @"10.1.0.1";
int udpPort = 6001;

AsyncUdpSocket *udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
[udpSocket bindToPort:udpPort error:nil];
[udpSocket enableBroadcast:YES error:nil]; 
NSError *error = nil;
if ([udpSocket connectToHost:bchost onPort:udpPort error:&error])
{
[udpSocket receiveWithTimeout:10 tag:0];
[self sendToUDPServer:@"HELLO"];
}

因此,问题在于它只能与主机一起使用,而不能与主机一起使用bchost。在这两种情况下,我都在服务器端看到接收到数据并将答案发送到发送方的地址(应该是iOS设备),但是在设备上,当我将其发送到bchost时却没有得到数据。

So, the problem is that it works with "host" but not with "bchost". On both cases I see on the server side that the data is received and the answer is sent to the address of the sender (which should be the iOS device) but on the device I do not get the data when I send it to bchost.

知道我想念的是什么吗?

Any idea what I am missing ?

推荐答案

好所有答复都对我不起作用,但最终我找到了解决方案;)

Ok, unfortunately all reply's do not work for me but I found the solution, finally ;)

NSString *bcHost = @"255.255.255.255";
NSString *anyHost = @"0.0.0.0";

int UDP_SOCKET_PORT =         6001;
int DISCOVERY_PORT  =       6003;

udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
[udpSocket bindToAddress:anyHost port:DISCOVERY_PORT error:nil];  
[udpSocket enableBroadcast:YES error:nil]; 
[udpSocket receiveWithTimeout:10 tag:0];
[udpSocket sendData:[@"Hello" dataUsingEncoding:NSASCIIStringEncoding] toHost:bcHost port:UDP_SOCKET_PORT withTimeout:-1 tag:0];

如果后面有服务器,它将触发响应,这也将允许获取ip从服务器进行进一步处理。

If there is an server behind it, it will trigger a response and this will also allow to get the ip from the server for further processing.

这篇关于连接到广播而不是服务器后,AsyncUdpSocket接收数据的小问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆