[英]iOS receive udp response from server
I'm successfully using the following code to send a UDP-message to a server: 我已成功使用以下代码将UDP消息发送到服务器:
GCDAsyncUdpSocket *udpSocket;
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSData *data = [@"initialize" dataUsingEncoding:NSUTF8StringEncoding];
[udpSocket sendData:data toHost:@"127.0.0.1" port:5000 withTimeout:-1 tag:1];
When the server receives this message it replies with a series of responses. 服务器收到此消息后,会回复一系列响应。 How can I catch and process those?
我该如何捕捉和处理这些? I want my app to listen to server-responses on the same port it sent the outgoing message for 2 minutes and then repeat the initialize-message in an endless loop:
我希望我的应用在发送外发消息的端口上监听服务器响应2分钟,然后在无穷循环中重复初始化消息:
message -> listen -> message -> listen ...
I was able to figure it out myself - was not to hard after all :-) 我自己就能弄清楚-毕竟并不辛苦:-)
To start listening in the background I simply used this: 要开始在后台收听,我只使用了以下方法:
NSError *error = nil;
if (![udpSocket bindToPort:0 error:&error])
{
NSLog(@"Error binding: %@", [error description]);
return;
}
if (![udpSocket beginReceiving:&error])
{
NSLog(@"Error receiving: %@", [error description]);
return;
}
To repeatetly send the initialiszation I used a timer initlilzieServer containes the code above): 为了重复发送初始化,我使用了一个计时器initlilzieServer包含上面的代码):
timer = [NSTimer scheduledTimerWithTimeInterval:150
target:self
selector:@selector(initializeServer)
userInfo:nil
repeats:YES];
And then I do the processing of the responses in this class: 然后,我在此类中处理响应:
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
NSString *msg = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
if (msg)
{
NSLog(@"%@",msg);
}
else
{
NSString *host = nil;
uint16_t port = 0;
[GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
NSLog(@"Unknown Message: %@:%hu", host, port);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.