【发布时间】:2014-03-31 12:38:48
【问题描述】:
我正在开发一个连接到另一台设备的应用程序,为了连接到它,我的应用程序必须找到它的 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 个小时里它让我非常头疼,所以如果你能帮助我,我将非常感激!
【问题讨论】:
-
收到一些数据后是否调用getHost?
-
这就是我调用 getHost 的方式:
UDPConnection *udpConnection = [[UDPConnection alloc] init]; [udpConnection activate]; host = [udpConnection getHost]; -
@HotLicks 请删除您的近距离投票,这个问题是关于网络,而不是关于在应用程序中的 VC 之间传递数据。
标签: ios iphone objective-c sockets asyncsocket