0

我将要发送到服务器的消息添加到队列中:

typedef struct StreamOutputQueue{
    char message[513];
    struct StreamOutputQueue * next;
} StreamOutputQueue;

当我收到事件 NSStreamEventHasSpaceAvailable 时,我发送队列中的第一条消息,然后将其删除,以便下一条消息准备好。如果队列为空,我会设置一个标志,以便我可以立即发送下一条消息而无需将其添加到队列中,因为流应该已准备好并且队列为空。

这是得到事件后的代码:

case NSStreamEventHasSpaceAvailable:
            NSLog(@"Space Available!");
            if (login_start) { //Login
                range = [nick_field.text rangeOfString: @" "]; //Find space in nickname text
                if (range.location != NSNotFound) { //Found so include only the text up to the space.
                    used_nick = [nick_field.text substringToIndex: range.location];
                }else{ //Else include it all
                    used_nick = nick_field.text;
                }
                [irc_output_stream write:(const uint8_t *)[[NSString stringWithFormat:@"USER %@ * * :%@ \r\nNICK %@\r\n", used_nick, nick_field.text,used_nick,nil] UTF8String] maxLength:1024]; //Send USER and NICK IRC commands
                login_start = NO; //Login done.
            }else if (output_queue){ //Queue exists
                printf("OUTPUT QUEUE HAS DATA - %s\n",output_queue->message);
                [irc_output_stream write: (const uint8_t *)output_queue->message maxLength:512]; //Send message to server.
                StreamOutputQueue * next = output_queue->next;
                free(output_queue);
                output_queue = next; //Queue pointer points to next node.
                space_available = NO;
            }else{
                space_available = YES; //Nothing sent, space available for immediate data delivery to server. 
            }
            break;

登录工作正常。登录完成后,程序开始在需要时使用队列发送消息。

这是将数据添加到队列末尾的代码:

- (void) appendToOutputQueue: (char *) message{
    if (space_available) { //Space available with no queue so send the next one now.
        printf("SPACE AVAILABLE NO QUEUE - %s",message);
        [irc_output_stream write: (const uint8_t *)message maxLength:512];
        space_available = NO; //Wait until space is available again
        return; //Do not continue to add to queue
    }
    //Add to queue
    StreamOutputQueue * new;
    new = malloc(sizeof(*new)); //Allocate new node
    new->next = NULL; //Next must be null to signify end
    strcpy(new->message,message); //Copy message data
    if (output_queue) { //If the queue exists add the node to the end
        output_queue_end->next = new;
    }else{ //Else make the queue start at this node
        output_queue = new;
    }
    output_queue_end = new; //The end node is now this one
}

问题是服务器无法识别通过队列发送的数据。数据在 printf 调用中正确打印。登录工作绝对正常。如果数据是在事件方法之外发送的,它似乎每次都失败,并且在某些时候失败,当它在事件方法中时,服务器会像收到损坏的数据一样行事。

这应该怎么做?

谢谢你。

4

1 回答 1

1

需要删除 const,我将 strlen 添加到 maxLength。

于 2011-05-14T21:29:38.803 回答