gpt4 book ai didi

iOS 从服务器接收 udp 响应

转载 作者:行者123 更新时间:2023-11-29 13:25:14 24 4
gpt4 key购买 nike

我成功地使用以下代码将 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];

当服务器收到此消息时,它会回复一系列响应。我怎样才能捕捉和处理那些?我希望我的应用程序在发送传出消息的同一端口上监听服务器响应 2 分钟,然后在无限循环中重复初始化消息:

message -> listen -> message -> listen ...

最佳答案

我自己弄明白了 - 毕竟并不难 :-)

为了开始在后台收听,我简单地使用了这个:

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;
}

为了重复发送初始化,我使用了一个计时器 initlilzieServer 包含上面的代码):

timer = [NSTimer scheduledTimerWithTimeInterval:150
target:self
selector:@selector(initializeServer)
userInfo:nil
repeats:YES];

然后我在这个类中处理响应:

- (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);
}
}

关于iOS 从服务器接收 udp 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13292682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com