我试图为iOS创建一个应用程序,在那里我可以连接到UDP服务器并从它接收数据。我的情况:连接到UDP服务器
- 我在Windows机器上有一个UDP服务器(IP = 192.168.1.6)。
- 我有iPad(IP = 192.168.1.5);
- UDP服务器发送到虚拟地址(IP = 239.254.1.2)和端口(7125)消息,如“你好!!!!!我在这里!!!!”
我需要为iOS应用程序添加一些逻辑,在那里我可以连接到虚拟IP地址(IP = 239.254.1.2)和端口(7125)并接收消息“你好!!!!!我在这里!!!!”来自UDP服务器。
有没有人有任何建议?
UPDATE1:
对于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地址的任何消息。 你能帮我解决这个问题吗?
谢谢。
你好,RichardBrock 谢谢你的回复。 我用我的测试源代码更新我的问题。你能回顾一下吗? 谢谢。 – kroumvud 2013-03-15 00:52:55