views:

106

answers:

2

I wrote a program that worked as a server. Knowing that "accept" was blocking the program. I wanted to launch a thread with this statement to prevent precisely that the program blocked, but this still happens. Can anybody help? Post code Thanks

-(IBAction)Connetti{

     if(switchConnessione.on){

      int port = [fieldPort.text intValue];

      labelStatus.text = [[NSString alloc] initWithFormat:@"Il Server è attivo"];

      server_len = sizeof(server);

      server.sin_family = AF_INET;
      server.sin_port = htons((u_short)port);
      server.sin_addr.s_addr = INADDR_ANY;

      sd = socket (AF_INET, SOCK_STREAM, 0);

      bind(sd, (struct sockaddr*)&server, sizeof(server));

      listen(sd, 1);

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

      }

     else {
      labelStatus.text = [[NSString alloc] initWithFormat:@"Server non attivo"]; 

      switchChat.on = FALSE;
      switchChat.enabled = FALSE;
     }

    } 

-(void)startThreadAccept{

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

     [self performSelectorOnMainThread:@selector(acceptConnection) withObject:nil waitUntilDone:NO];
     [pool release];

    }

-(void)acceptConnection{

     new_sd = accept(sd, (struct sockaddr*)&server, &server_len);
     labelStatus.text = [[NSString alloc] initWithFormat:@"Ho accettato una connessione:%d", new_sd];
     switchChat.enabled = TRUE;



}
A: 

You still call accept() on the main thread. If you want the connection to be accepted on a different thread, then you need to remove the -performSelectorOnMainThread: call.

Graham Lee
So this might be a good solution? (Below)
zp26
A: 

this is my new methods

-(IBAction)Connetti{

//code 
[NSThread detachNewThreadSelector:@selector(acceptConnection) toTarget:self withObject:nil]; 
//code   
} 

-(void)acceptConnection{

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

new_sd = accept(sd, (struct sockaddr*)&server, &server_len); 
labelStatus.text = [[NSString alloc] initWithFormat:@"Ho accettato una connessione:%d", new_sd]; 
switchChat.enabled = TRUE; 
[pool   release]; 

} 

It 's a correct solution? Why in some occasions, the thread seems to not start? Thanks

zp26
That's better, but each accept probably leaks a string (assuming that labelStatus is an object and text is a retain or copy property on that object). You probably want [NSString stringWithFormat: ....]
JeremyP