我正在尝试为 iOS 创建一个应用程序,我可以在其中连接到 UDP 服务器并从中接收数据。我的情况:
- 我在 Windows 机器上有一个 UDP 服务器(IP = 192.168.1.6)。
- 我有 iPad(IP = 192.168.1.5);
- UDP 服务器向虚拟地址 (IP = 239.254.1.2) 和端口 (7125) 发送消息,例如“HELLO!!!!!!我在这里!!!”
我需要为 iOS 应用程序添加一些逻辑,我可以在其中连接到虚拟 IP 地址 (IP = 239.254.1.2) 和端口 (7125) 并接收消息“你好!!!!!我在这里!!!” 来自 UDP 服务器。
有没有人有什么建议?
更新1:
对于 UDP 连接,我使用GCDAsyncUdpSocket
这是我的代码:
@interface ViewController () {
GCDAsyncUdpSocket *udpSocket;
}
- (void)viewDidLoad {
[super viewDidLoad];
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
}
- (IBAction)startStop:(id)sender {
if (isRunning) {
// STOP udp echo server
[udpSocket close];
[self logInfo:@"Stopped Udp Echo server"];
isRunning = false;
[portField setEnabled:YES];
[startStopButton setTitle:@"Start" forState:UIControlStateNormal];
} else {
// START udp echo server
int port = [portField.text intValue];
if (port < 0 || port > 65535) {
portField.text = @"";
port = 0;
}
NSError *error = nil;
if (![udpSocket bindToPort:7125 error:&error]) {
[self logError:FORMAT(@"Error starting server (bind): %@", error)];
return;
}
if (![udpSocket joinMulticastGroup:@"239.254.1.2" error:&error]) {
[self logError:FORMAT(@"Error join Multicast Group: %@", error)];
return;
}
if (![udpSocket beginReceiving:&error])
{
[udpSocket close];
[self logError:FORMAT(@"Error starting server (recv): %@", error)];
return;
}
[self logInfo:FORMAT(@"Udp Echo server started on port %hu", [udpSocket localPort])];
isRunning = YES;
[portField setEnabled:NO];
[startStopButton setTitle:@"Stop" forState:UIControlStateNormal];
}
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
if (!isRunning) return;
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (msg)
{
/* If you want to get a display friendly version of the IPv4 or IPv6 address, you could do this:
NSString *host = nil;
uint16_t port = 0;
[GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
*/
[self logMessage:msg];
}
else
{
[self logError:@"Error converting received data into UTF-8 String"];
}
[udpSocket sendData:data toAddress:address withTimeout:-1 tag:0];
}
当我在日志中按“开始”按钮时,我看到消息“Udp Echo 服务器在端口 7125 上启动”,但委托方法
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
从未触发,应用程序不会收到来自虚拟 IP 地址的任何消息。你能帮我解决这个问题吗?
谢谢你。