不确定这是否会有所帮助,但我遇到了同样的问题,这就是我解决它的方法。
就我而言,问题在于:
[self.socket receiveWithTimeout:-1 tag:0];
位于“错误”的地方。
如果你调用[self.socket receiveWithTimeout:-1 tag:0]; 在方法didFinishLaunchingWithOptions中,无论您做什么,套接字都不会工作(即使您尝试在新线程中启动它)。为了解决这个问题,我制作了一个按钮并将receiveWithTimeout调用移动到单击该按钮时调用的方法。我的猜测是 ASyncUdpSocket 不喜欢didFinishLaunchingWithOptions中的线程处理。
我在下面发布了我的工作示例代码(使用 XCode 5.1.1)。这些是我的 Xcode 项目的完整 AppDelegate 文件。
AppDelegate.h
#import <UIKit/UIKit.h>
#import "AsyncUdpSocket.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate, AsyncUdpSocketDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) AsyncUdpSocket *udpSocket;
@property (strong, nonatomic) UILabel *receiver;
@end
AppDelegate.m
#import "AppDelegate.h"
#import "AsyncUdpSocket.h"
#import <UIKit/UIKit.h>
#import <CFNetwork/CFNetwork.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Create the main window
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
// Create a label for showing received text
self.receiver = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 80.0)];
self.receiver.text = @"No message, yet!";
self.receiver.textColor = [UIColor blackColor];
[self.window addSubview:self.receiver];
// Create a button for sending messages
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(80.0, 210.0, 160.0, 40.0)];
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Start Game" forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor blueColor]];
[self.window addSubview:button];
@try {
self.udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
if (![self.serverSocket bindToPort:9003 error:nil]) {
NSLog(@"COULD NOT BIND TO PORT");
}
if (![self.udpSocket enableBroadcast:YES error:nil]) {
NSLog(@"COULD NOT ENABLE BROADCASTING");
}
} @catch (NSException * e) {
NSLog(@"Exception: %@", e);
}
return YES;
}
- (void)buttonClick:(UIButton*)button {
NSData * data = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];
[self.udpSocket receiveWithTimeout:-1 tag:0];
if (![self.udpSocket sendData:data toHost:@"127.0.0.1" port:9003 withTimeout:0.2 tag:1]) {
NSLog(@"COULD NOT SEND DATA");
} else {
NSLog(@"Sent packet (from %@:%d to 127.0.0.1:9001)", self.udpSocket.localHost, self.udpSocket.localPort);
}
}
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port {
NSLog(@" Received data (from %@:%d) - %@", host, port, data);
self.receiver.text = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[self.udpSocket receiveWithTimeout:-1 tag:0];
return YES;
}
@end
希望这对某人有帮助。