我写了一个作为服务器的程序。 知道“接受”阻止了该计划。 我想用这个语句启动一个线程,以防止程序被阻止,但这仍然会发生。 有人可以帮忙吗? 邮政编码 感谢
-(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;
}
答案 0 :(得分:0)
你仍然在主线程上调用accept()
。如果您希望在其他线程上接受连接,则需要删除-performSelectorOnMainThread:
电话。
答案 1 :(得分:0)
这是我的新方法
- (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];
}
这是一个正确的解决方案吗?为什么在某些情况下,线程似乎无法启动?感谢