我正在开发一个连接到另一个设备的应用程序,为了连接到它,我的应用程序必须找到它的IP。我是通过UDP套接字做的。我正在向另一台设备中的服务器应用程序发送消息,然后服务器应用程序向我发送另一条消息,但在我收到消息后,我只使用IP地址。然后我想从这个.m
文件到另一个.m
文件,它将在两个设备之间建立TCP连接。这是我使用的代码:
NSString *SearchCommand = @"AT+S";
static int receivedByteCount = 0;
BOOL connectedThroughUDP;
- (void) activate {
connectedThroughUDP = NO;
AsyncUdpSocket *udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
[udpSocket bindToPort:1234 error:nil ];
[udpSocket enableBroadcast:YES error:nil];
NSData* data=[SearchCommand dataUsingEncoding:NSUTF8StringEncoding];
if ([udpSocket sendData:data toHost:@"255.255.255.255" port:30100 withTimeout:3 tag:0])
{
//2 second timeout. onUdpSocket methods will provide results
[udpSocket receiveWithTimeout:2 tag:0];
NSLog(@"Connected.");
}
}
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
NSString *receiveddata = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
addressOfServer = host;
NSLog(@"addressOfServer = %@", addressOfServer);
connectedThroughUDP = YES;
return YES;
}
- (NSString *) getHost {
return addressOfServer;
}
- (BOOL) isItConnected {
return connectedThroughUDP;
}
addressOfServer是全局变量。
在我想要的日志NSLog(@"addressOfServer = %@", addressOfServer);
中,我收到了我想要的IP地址,但是当我想通过getHost
方法访问时,我会收到(null)
。
我知道这将是非常简单的事情,但在过去的3个小时里让我感到头痛,所以如果你能帮助我,我会非常感激!
答案 0 :(得分:0)
你是否正好将这三行称为对方:
UDPConnection *udpConnection = [[UDPConnection alloc] init];
[udpConnection activate];
host = [udpConnection getHost];
如果是这样,您的问题是[udpConnection activate];
需要一些时间来连接并找出地址。您过早地致电[udpConnection getHost];
。
您需要设置在didReceiveData
被解雇时触发的委托或完成块