iphone UDP监听器/服务器 - 没有获得数据回调

时间:2011-02-10 17:44:28

标签: iphone sockets callback udp

我有一个问题,我没有从CF套接字获得数据回调。我的应用程序允许用户设置最多4个数据传输通道(我称之为“试验”,因为我不知道通道是否意味着特定的东西。)到目前为止,我只在模拟器中进行测试,并且我只使用UDP。对于每个试验,我初始化我的套接字驱动程序类的新实例(模拟器情况称为SimSocket,分别初始化为发布者或订阅者发送或接收),发送/接收相对少量的数据,然后关闭套接字并释放SimSocket。然后我再做一次试验等等。

以下是失败的原因:我将试验#0设置为接收器,然后设置试验#1将数据发送到127.0.0.1。我启动接收器,然后发送器,数据传输工作正常。我可以一遍又一遍地重复这个,没有问题。然后,在不更改任何IP或端口地址或数据包大小或数据包速率的情况下,我只运行试验1,因此数据将发送到以太网或某处。发生这种情况时,我的控制台输出中没有任何问题。接下来我再次启动接收器,试验0,然后运行发送器,试用1.但是现在我从未看到任何数据回调,并且试验0从未获得任何数据处理。我的问题是,为什么试验0在该序列之后无法接收数据?

一些支持信息....我在Mac上运行Wireshark查看环回接口。即使在试验0失败的运行中,我仍然可以看到Wireshark中的UDP数据报,我希望看到它。对于上面描述的整个序列,我在我的控制台输出中看到套接字总是被正确打开和关闭(除了最后一个失败的试验0 - 当然它永远不会到达关闭点)。所有接收代码都在主线程上执行。当我发送一组数据时,我会在一个单独的线程上执行此操作,但是当事情有效并且没有时则相同。当以2 Kbps发送10个50字节“原始数据包”时,我可能会遇到此故障。

以下是我的SimSocket实现文件的相关部分。我感谢您提供的任何帮助。感谢。

#import "SimSocket.h"

void simReceivedDataCallback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) {
    // NOTE: I don't know if I'm accessing the address argument properly here, or if it contains useful information!
    NSLog(@"SimSocket: simReceivedDataCallback function entry. Socket=%d, address=%s, port=%d", CFSocketGetNative(s), inet_ntoa(((struct sockaddr_in *)address)->sin_addr), htons(((struct sockaddr_in *)address)->sin_port));
        // send data to SimSocket delegate here
}

@implementation SimSocket

@synthesize readyToUse, delegate, errors;

- (id)initWithType:(SimSocketConnection)connectionType1 host:(NSString *)host1 port:(int)port1 {
    if (self = [super init]) {
        hostStr = host1;
        port = port1;
        isPublish = YES;
        connectionType = connectionType1;
        readyToUse = NO;

        int sockType = (connectionType == SimSocketConnectionTcp) ? SOCK_STREAM : SOCK_DGRAM;
        sockfd = socket(AF_INET, sockType, 0);
        if (sockfd == -1) {
            NSLog(@"SimSocket:initWithType: Error with socket() - %s", strerror(errno));
            return self;
        }

        memset((void *)&address_in, 0, sizeof(address_in));
        address_in.sin_family = AF_INET;
        address_in.sin_port = htons(port);
        address_in.sin_addr.s_addr = inet_addr([hostStr UTF8String]);
        addressData = [NSData dataWithBytes:&address_in length:sizeof(address_in)];

        readyToUse = YES;
        return self;
    }
    else {
        return nil;
    }
}

- (id)initPublishWithType:(SimSocketConnection)connectionType1 host:(NSString *)host1 port:(int)port1 {
   if ([self initWithType:connectionType1 host:host1 port:port1]) {
      readyToUse = NO;
       NSLog(@"SimSocket:initPublishWithType: Successfully created BSD socket - %d", sockfd);

      cfsocket = CFSocketCreateWithNative(NULL, sockfd, kCFSocketConnectCallBack, simCallback, NULL);
      if (cfsocket == NULL) {
         NSLog(@"SimSocket:initPublishWithType: Error with CFSocketCreateWithNative()");
         return self;
      }
      readyToUse = YES;
   }
   return self;
}

- (id)initSubscribeWithType:(SimSocketConnection)connectionType1 host:(NSString *)host1 port:(int)port1 delegate:(id <SimSocketEvents>)delegate1 {
    NSLog(@"SimSocket:initSubscribeWithType: starting initialization with delegate %@", delegate1);

    if ([self initWithType:connectionType1 host:host1 port:port1]) {
        readyToUse = NO;
        NSLog(@"SimSocket:initSubscribeWithType: Successfully created BSD socket - %d", sockfd);

        delegate = delegate1;
        address_in.sin_addr.s_addr = htonl(INADDR_ANY);
        addressData = [NSData dataWithBytes:&address_in length:sizeof(address_in)];

        int yes = 1;
        if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
            NSLog(@"SimSocket:initSubscribeWithType: Error with setsockopt() with SO_REUSEADDR - %s", strerror(errno));
        }

        if (bind(sockfd, (struct sockaddr*) &address_in, sizeof(address_in)) == -1) {
            NSLog(@"SimSocket:initSubscribeWithType: Error with bind() - %s", strerror(errno));
            errors = [NSString stringWithFormat:@"Bind Failed - %s. Try using a Different Port number.", strerror(errno)];
            close (sockfd);
            return self;
        }

        CFSocketContext context = { 0, (void *)self, NULL, NULL, NULL };

        // TCP
        if (connectionType == SimSocketConnectionTcp) {
            if (listen(sockfd, 10) == -1) {
                NSLog(@"SimSocket:initSubscribeWithType: Error with listen() - %s", strerror(errno));
                return self;
            }
            cfsocket = CFSocketCreateWithNative(NULL, sockfd,  kCFSocketAcceptCallBack, simAcceptCallback, &context);
        }
        // UDP
        else if (connectionType == SimSocketConnectionUdp) {
            cfsocket = CFSocketCreateWithNative(NULL, sockfd,  kCFSocketDataCallBack, simReceivedDataCallback, &context);

        }

        if (cfsocket == NULL) {
            NSLog(@"SimSocket:initSubscribeWithType: Error with CFSocketCreateWithNative()");
            return self;
        }

        CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(NULL, cfsocket, 0);
        CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
        CFRelease(source);
        NSLog(@"SimSocket:initSubscribeWithType: Current run loop = %x.  Main thread run loop = %x.", CFRunLoopGetCurrent(), CFRunLoopGetMain());

        readyToUse = YES;
        NSLog(@"SimSocket:initSubscribeWithType: Completed socket initialization successfully.");
    }
    return self;
}

- (void)dealloc {
    if (cfsocket) CFRelease(cfsocket);
    if (sockfd != -1) close(sockfd);
    [errors release];
    [super dealloc];
}

-(void)shutdown
{
    NSLog(@"SimSocket: shutdown: Am shutting down the socket.  sockfd = %d", sockfd);   
    if (cfsocket) CFRelease(cfsocket);
    if (sockfd != -1) close(sockfd);
}

- (void)sendBytes:(const void *)bytes length:(int)length {
   if (!readyToUse) {
      NSLog(@"SimSocket:sendBytes: socket not ready to use for sending");
      return;
   }

   int bytesSent;
   if (connectionType == SimSocketConnectionTcp) {
      bytesSent = send(sockfd, bytes, length, 0); 
   }
   else {
      bytesSent = sendto(sockfd, bytes, length, 0, (struct sockaddr *)&address_in, sizeof(address_in)); 
   }

    if (bytesSent < 0) {
        NSLog(@"SimSocket:sendBytes: Oops, error- %s. No bytes sent.", strerror(errno));
    }
    else if (bytesSent < length) {
        NSLog(@"SimSocket:sendBytes: Oops, error- %s. Only %i sent out of %i", strerror(errno), bytesSent, length);
    }
    else {
        NSLog(@"SimSocket:sendBytes: Successfully sent the packet (%d bytes) to %s", length, inet_ntoa(address_in.sin_addr));
    }
    NSLog(@"SimSocket:sendBytes: Current run loop = %x.  Main thread run loop = %x.", CFRunLoopGetCurrent(), CFRunLoopGetMain());
}

@end

1 个答案:

答案 0 :(得分:3)

伙计们,看起来我发现了问题。关闭事情时,我只是发布了CFSocket。在UDPEcho示例项目的引导下,我将其替换为3个步骤:CFSocketInvalidate调用,CFRelease调用,然后将CFSocket引用设置为NULL。现在似乎工作正常。