开发者

while(1) block my recv thread

开发者 https://www.devze.com 2022-12-27 04:57 出处:网络
I have a problem with this code. As you can see a launch with an internal thread recv so that the program is blocked pending a given but will continue its execution, leaving the task to lock the threa

I have a problem with this code. As you can see a launch with an internal thread recv so that the program is blocked pending a given but will continue its execution, leaving the task to lock the thread. My program would continue to receive the recv data socket new_sd and so I entered an infinite loop (the commented code). The problem is that by entering the while (1) my program block before recv, but not inserting it correctly receives a string, but after that stop. Someone could help me make my recv al开发者_开发知识库ways waiting for information? Thanks in advance for your help.

-(IBAction)Chat{

      [NSThread detachNewThreadSelector:@selector(riceviDatiServer) toTarget:self withObject:nil];  

}

-(void)riceviDatiServer{

 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];

 labelRicevuti.text = [[NSString alloc] initWithFormat:@"In attesa di ricevere i dati"];

 char datiRicevuti[500];
 int ricevuti;

    //while(1){
 ricevuti = recv(new_sd, &datiRicevuti, 500, 0);

 labelRicevuti.text = [[NSString alloc] initWithFormat:@"%s", datiRicevuti];
    //}

 [pool release];

}


You shouldn't use a while( 1 ) loop, as it will prevent your thread to receive information.
You should take a look at the NSRunLoop class.

[EDIT]
As requested, here's an example of a basic Obj-C program that uses a run-loop. : )

#import <Cocoa/Cocoa.h>

BOOL loopShoudRun = YES;

int main( void )
{
    NSAutoreleasePool * pool;
    NSRunLoop         * loop;

    pool = [ [ NSAutoreleasePool alloc ] init ];
    loop = [ NSRunLoop currentRunLoop ];

    while( loopShoudRun == YES && [ loop runMode: NSDefaultRunLoopMode beforeDate: [ NSDate distantFuture ] ] );

    [ pool release ]
    return 0;
}


labelRicevuti.text = [[NSString alloc] initWithFormat:@"In attesa di ricevere i dati"];

This line leaks the string you have allocated unless labelRicevuti is an ordinary C struct.

char datiRicevuti[500];
int ricevuti;

//while(1){
ricevuti = recv(new_sd, &datiRicevuti, 500, 0);

You never check ricevuti to see if it is -1 here.

labelRicevuti.text = [[NSString alloc] initWithFormat:@"%s", datiRicevuti];

This line probably seg faults, because datiRicevuti is almost certainly not a null terminated sequence of chars. Firstly, you never zeroed out the buffer before using it. Secondly, you allow recv to fill it up completely if it has 500 or more bytes available, so there's no space for a terminating nul.

Also, you leak the allocated string, unless labelRicevuti is an ordinary C struct, in which case you leak the string allocated in the previous iteration or the one at the top of the function.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号