【发布时间】:2016-04-11 12:21:11
【问题描述】:
我目前正在使用GCDAsyncUdpSocket 库并成功向服务器发送 UDP 消息,但是当发送 125 条消息时,应用停止发送消息但不会崩溃或抛出任何错误。
这是一个问题,因为我不断发送消息来控制机器人的运动。
这是发送消息的视图的 .m 文件。
非常感谢任何帮助。
#import "MovementVC.h"
#import "GCDAsyncUdpSocket.h"
@interface MovementVC ()
@end
@implementation MovementVC
- (void)viewDidLoad {
[super viewDidLoad];
f, r, l, b = false;
timer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target:self selector:@selector(targetMethod:) userInfo:nil repeats:YES];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)RightTouchDown:(id)sender {
r = true;
}
- (IBAction)RightTouchUpIn:(id)sender {
r = false;
}
- (IBAction)RightTouchUpOut:(id)sender {
r = false;
}
- (IBAction)ForwardTouchDown:(id)sender {
f = true;
}
- (IBAction)ForwardTouchUpIn:(id)sender {
f = false;
}
- (IBAction)ForwardTouchUpOut:(id)sender {
f = false;
}
- (IBAction)LeftTouchDown:(id)sender {
l = true;
}
- (IBAction)LeftTouchUpIn:(id)sender {
l = false;
}
- (IBAction)LeftTouchUpOut:(id)sender {
l = false;
}
- (IBAction)ReverseTouchDown:(id)sender {
b = true;
}
- (IBAction)ReverseTouchUpIn:(id)sender {
b = false;
}
- (IBAction)ReverseTouchUpOut:(id)sender {
b = false;
}
-(void) sendUDPMessage: (NSString*)messageToSend
{
GCDAsyncUdpSocket *udpSocket ; // create this first part as a global variable
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSData *data = [messageToSend dataUsingEncoding:NSUTF8StringEncoding];
[udpSocket sendData:data toHost:@"172.31.0.1" port:43211 withTimeout:-1 tag:1];
}
-(void) targetMethod:(id)sender
{
if (r == TRUE)
{
[self sendUDPMessage: @"1"];
}
else if (l == TRUE)
{
[self sendUDPMessage: @"11"];
}
else if(f == TRUE)
{
[self sendUDPMessage: @"111"];
}
else if (b == TRUE)
{
[self sendUDPMessage: @"1111"];
}
}
@end
【问题讨论】:
-
我认为您需要在发送消息后进行清理。可以打开的套接字数量可能有限制,我看不出你在哪里关闭它们。在委托方法 udpSocket:didSendDataWithTag: 或 udpSocket:didNotSendDataWithTag:dueToError: 中执行此操作,并确保关闭套接字。
-
或者重用同一个套接字:不是每次都分配一个新套接字,而是通过将套接字设为您的 MovementVC 的@property 来使其可重用
标签: ios networking udp