Fork me on GitHub

socket的udp编程

int globalsoc;

 

-(void)searchFunction {
    isSearch = YES;
    isConnect = NO;
    if (isfirstSearch == YES) {
        isfirstSearch = NO;
        globalsoc = socket(AF_INET, SOCK_DGRAM, 0);
        if (globalsoc == -1){

            //error
            NSLog([NSString stringWithFormat:@"failed to create socket(receive) : %d", errno]);
            return;
        }
        NSLog(@"creat socket");
        [NSThread detachNewThreadSelector:@selector(recieveMsgThread) toTarget:self withObject:nil];
        [NSThread sleepForTimeInterval:0.5];
        [self performSelectorOnMainThread:@selector(sendMsgThread) withObject:nil waitUntilDone:NO];
    }
    else {
        [otherList release];
        otherList = nil;
        [otherListIp release];
        otherListIp = nil;
        
        globalsoc = socket(AF_INET, SOCK_DGRAM, 0);
        if (globalsoc == -1){
//            NSLog([NSString stringWithFormat:@"failed to create socket(receive) : %d", errno]);
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"メッセージ" message:@"ネットワークに接続できません" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        }
        NSLog(@"creat socket");

        //线程接收,如没有数据,挂起等待(后台)
        [NSThread detachNewThreadSelector:@selector(recieveMsgThread) toTarget:self withObject:nil];
        [NSThread sleepForTimeInterval:0.5];

        //主线程,发送数据
        [self performSelectorOnMainThread:@selector(sendMsgThread) withObject:nil waitUntilDone:NO];        
        //        [self sendMsgThread];
    }
    
    [table reloadData];
    
}

posted on 2012-05-17 08:57  pengyingh  阅读(147)  评论(0)    收藏  举报

导航