1

好的,基本上我的应用程序每隔一两秒就会有一个运行循环,同时我还有另一个线程正在循环通过该listenForPackets方法;broadcastMessage仅在发生另一种操作方法时才启动。这个问题的重要部分是,当侦听器线程与主线程分开运行时,它永远不会打印出任何打印命令,而且它似乎不允许访问我定义的名为的全局变量,该变量recvMessage位于接口和实现部分。

在我的代码中,我对其进行了设置,以便每次运行主运行循环时,它都会更新我的 GUI 中的 UILabel。当应用程序运行时,我的标签一直保持空白并且永远不会改变。我已经仔细检查了 GUI,所有内容都正确链接在那里,我的标签也被正确实例化(我在下面的代码中使用名称“标签”作为 UILabel 的实例)。有人知道为什么我的标签会更新吗?我相信事物的网络方面很好,因为我刚刚完成了,一切都在“交谈”。也许这是一个我不知道的变量范围问题,或者是否允许单独的线程访问全局变量,例如我在下面使用的那个(rcvMessage)?我对多线程应用程序相当陌生,但我不相信它真的很难实现,

全局变量

NSString *recvMessage;

Main Runloop - 每次通过 runloop 时更新标签的部分

if (label.text != recvMessage)
    label.text = recvMessage

说话者法

-(void)broadcastMessage { // (NSString*)msg {
    msg = @"From_Master";

    NSLog(@"broadcastMessage - Stage 1");
    mc_ttl = 15; // number of node hops the message is allowed to travel across the network
    // define the port we will be using
    mc_port = MYPORT;

    // create a socket for sending to the multicast address
    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
        NSLog(@"ERROR: broadcastMessage - socket() failed");
        return;
    }

    memset(&mc_addr, 0, sizeof(mc_addr));
    mc_addr.sin_family      = AF_INET;
    mc_addr.sin_addr.s_addr = inet_addr(GROUP_ADDRESS);
    mc_addr.sin_port        = htons(MYPORT);

    NSLog(@"broadcastMessage - Stage 2");

// set the TTL (time to live/hop count) for the send
    if ((setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &mc_ttl, sizeof(mc_ttl))) < 0) {
        NSLog(@"ERROR: broadcastMessage - setsockopt() failed");
        return;
    }   

    NSLog(@"broadcastMessage - Stage 3");

    // clear send buffer
    memset(send_str, 0, sizeof(send_str));

    // convert the message to a C string to send
    [msg getCString:send_str maxLength:MAX_LEN encoding:NSASCIIStringEncoding];

    //while (fgets(send_str, MAX_LEN, stdin)) {
    NSLog(@"broadcastMessage - Stage 4");
    NSLog(@"Message =");
    printf(send_str);

    // send string to multicast address
    if ((sendto(sock, send_str, sizeof(send_str), 0, (struct sockaddr *)&mc_addr, sizeof(mc_addr))) < 0) {
        NSLog(@"ERROR: broadcastMessage - sendto() sent incorrect number of bytes");
        //return;
    }
    NSLog(@"Sent Message -");
    printf(send_str);
    NSLog(@"broadcastMessage - Stage 5");

    // clear send buffer
    memset(send_str, 0, sizeof(send_str));
    NSLog(@"broadcastMessage - Stage 6 - Complete");
    close(sock);
}

侦听器方法

-(void)listenForPackets {
    listeningFlag_on = 1; // allows reuse of the same socket

    NSLog(@"listenForPackets - Stage 1");
    if ((listeningSock = socket(AF_INET, SOCK_DGRAM,IPPROTO_UDP)) < 0) {
        NSLog(@"ERROR: listenForPackets - socket() failed");
        return;
            // make the method return an int instead of void and use this statement to check for errors
    }

    NSLog(@"listenForPackets - Stage 2");

    // set reuse port to on to allow multiple binds per host
    if ((setsockopt(listeningSock, SOL_SOCKET, SO_REUSEADDR, &listeningFlag_on, sizeof(listeningFlag_on))) < 0) {
        NSLog(@"ERROR: listenForPackets - setsockopt() Reuse failed");
        return;
            // make the method return an int instead of void and use this statement to check for errors
    }

    // construct a multicast address structure after erasing anything in the listeningmc_addr structure
    memset(&listeningmc_addr, 0, sizeof(listeningmc_addr));
    listeningmc_addr.sin_family      = AF_INET;
    listeningmc_addr.sin_addr.s_addr = htonl(INADDR_ANY); // different from sender
    listeningmc_addr.sin_port        = htons(MYPORT);

    // bind multicast address to socket
    if ((bind(listeningSock, (struct sockaddr *)&listeningmc_addr, sizeof(listeningmc_addr))) < 0) {
        NSLog(@"ERROR: listenForPackets - bind() failed");
        perror("Bind() -");
        return;                         // make the method return an int instead of void and use this statement to check for errors
    }

    //*********************************************************************************

    NSString *ipAddress = [[NSString alloc] initWithString:self.getIPAddress];
    const char *tmp = [ipAddress UTF8String];
    listeningMc_addr_str = tmp;

    printf("%s\n", listeningMc_addr_str);

    listeningMc_req.imr_multiaddr.s_addr = inet_addr(GROUP_ADDRESS);
    listeningMc_req.imr_interface.s_addr = htonl(INADDR_ANY);
    // send an ADD MEMBERSHIP message via setsockopt
    if ((setsockopt(listeningSock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &listeningMc_req, sizeof(listeningMc_req))) < 0) {
        NSLog(@"ERROR: listenForPackets - setsockopt() failed");
        int err = errno;
        NSLog(@"errno - %i", err);
        NSLog(@"Error = %s", strerror(err));
        perror("ERROR");
        return;                         // make the method return an int instead of void and use this statement to check for errors
    }

    NSLog(@"listenForPackets - Stage 3");
    for (;;) {          // loop forever

        // clear the receive buffers & structs
        memset(listeningRecv_str, 0, sizeof(listeningRecv_str));
        listeningFrom_len = sizeof(listeningFrom_addr);
        memset(&listeningFrom_addr, 0, listeningFrom_len);

        NSLog(@"Test #1 Complete");
        //msgStatus.text = @"Waiting...";

        // block waiting to receive a packet
        listeningFrom_len = sizeof(listeningmc_addr);
        if ((listeningRecv_len = recvfrom(listeningSock, listeningRecv_str, MAX_LEN, 0, (struct sockaddr*)&listeningmc_addr, &listeningFrom_len)) < 0) {
            NSLog(@"ERROR: listenForPackets - recvfrom() failed");
            return;                     // make the method return an int instead of void and use this statement to check for errors
        }
        NSLog(@"Test #2 Complete - Received a Message =");
        NSLog(@"listenForPackets - Stage 4");

        // listeningRecv_str
    **tmpString = [[NSString alloc] initWithCString:listeningRecv_str encoding:NSASCIIStringEncoding];
            NSLog(@"Message Received =");
            NSLog(tmpString);
            recvMessage = tmpString;**
        //}
        // received string
        printf("Received %d bytes from %s: ", listeningRecv_len, inet_ntoa(listeningFrom_addr.sin_addr));
        printf("%s", listeningRecv_str);
        //}
    }
    // send a DROP MEMBERSHIP message via setsockopt
    if ((setsockopt(listeningSock, IPPROTO_IP, IP_DROP_MEMBERSHIP, (void*) &listeningMc_req, sizeof(listeningMc_req))) < 0) {
        NSLog(@"ERROR: listenForPackets - setsockopt() drop membership failed");
        //return 1;                         // make the method return an int instead of void and use this statement to check for errors
    }
    close(listeningSock);
    NSLog(@"listenForPackets - Stage 5 - Complete");
}
4

2 回答 2

4

是的,所有线程都可以访问全局变量。使用全局变量的方式肯定存在问题——每次更新变量时都会泄漏创建的 NSString,并且在没有任何访问控制的情况下从两个线程访问相同的内存——但是没有什么可以阻止变量从被更新。

如果没有打印任何日志消息,则问题是代码从未运行,这就是变量没有改变的原因。你应该看看应该启动这个新线程的代码。

于 2009-07-25T23:30:44.170 回答
0

另请注意,更新任何 UI 组件时,您需要使用方法“performSelectorOnMainThread”对标签文本或任何其他 GUI 元素进行任何值设置。该值不会从后台线程更新。

于 2009-07-27T01:15:29.947 回答