当我使用AsyncUdpSocket对象发送IP数据包时,它并不总是有效

时间:2013-08-16 05:36:12

标签: ios objective-c cocoaasyncsocket

我正在使用cocoaAsyncSocket。我是从there得到的。 AsyncUdpSocket对象仅在我初始化此对象时帮助我发送IP数据包。当我使用[engineObject startSession]来调用其他控制器中的函数时,该函数正在运行,但是AsyncUdpSocket对象不会发送任何IP数据包。它不会调用(或触发)委托方法:didSendDataWithTag或didNotSendDataWithTag .....

我做错了什么?

.h

#import <Foundation/Foundation.h>
#import "AsyncUdpSocket.h"

@interface Engine : NSObject{
    AsyncUdpSocket *asyncUdpSocket;
}
@property (atomic, strong) AsyncUdpSocket *asyncUdpSocket;
- (id) init;
- (BOOL) startSession;
- (void) doSomething;
@end

的.m

@implementation Engine

- (id) init {
    [self doSomething];  //<-----<< It can send ip packet out

    self = [super init];

    [self doSomething];  //<-----<< It can send ip packet out, with wrong bind source port
    if (self){

    }
    return self;
}

- (BOOL) startSession{
    [self doSomething]; //<-----<< It won't send any ip packet out 
    [self oxox];
    return YES;
}

- (void) oxox{

    [self doSomething]; //<-----<< It won't send any ip packet out 

}

- (void) doSomething{
    NSError *socketError=nil;
    asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
    if (![asyncUdpSocket bindToPort:7701
                              error:&socketError]){
        NSLog(@"RASEngine:    Bind to Port fail");
    }
    [asyncUdpSocket enableBroadcast:NO error:&socketError];
    uint8_t signalBytes[] = {0x07, 0x07, 0x01, 0x06, 0x12, 0x34, 0x56, 0x78};
    NSData *signalData = [NSData dataWithBytes:signalBytes length:8];

    [asyncUdpSocket sendData:signalData   //<--------<< It is called every time, but doesn't send anything out.  
                      toHost:@"192.168.16.18"
                        port:9902
                 withTimeout:-1
                         tag:0];
}

#pragma mark -
#pragma mark AsyncUdpSocket Delegate for UDP
- (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
    NSLog(@"UDP Engine:    onUdpSocket:didSendDataWithTag:%ld", tag);   
}


- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
    NSLog(@"UDP Engine:    onUdpSocket:didNotSendDataWithTag:%ld", tag);    
}

@end

1 个答案:

答案 0 :(得分:0)

经过一周的战斗,我发现问题是由RunLoop造成的。我使用GCDAsyncUDPStoket替换AsynvUdpSocket,然后问题解决了!

GCDAsyncUdpSocket *gcdAsyncUdpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self
                                                                     delegateQueue:dispatch_get_main_queue()];