Sportica   Sportica

基于UDP iOS 聊天


//首先建立基于UDP的Socket连接  AsyncUdpSocket *updSocket
-(void)openUDPServer{
    //初始化udp
    AsyncUdpSocket *tempSocket=[[AsyncUdpSocket alloc] initWithDelegate:self];
    self.updSocket=tempSocket;
    [tempSocket release];
    //绑定端口
    NSError *error = nil;
    [self.updSocket bindToPort:4333 error:&error];
    [self.updSocket joinMulticastGroup:@"224.0.0.1" error:&error];
    
       //启动接收线程
    [self.updSocket receiveWithTimeout:-1 tag:0];
    
}


//连接建好后处理相应send Events
-(void)sendMessage:(NSString*)message
{
    NSMutableString *sendString = [NSMutableString stringWithCapacity:100];
    [sendString appendString:message];
    //开始发送
    BOOL res = [self.updSocket sendData:[sendString dataUsingEncoding:NSUTF8StringEncoding] 
                                 toHost:@"224.0.0.1"
                                   port:4333 
                            withTimeout:-1 
                                    tag:0];
    
    NSLog(@"%@",sendString);
    if(res)
    {
        NSLog(@"xxxxffff");
    }
    else {
        NSLog(@"error");
    }
}



-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"onUdpSocket successful");
    //已经处理完毕  do something
    return YES;
}

-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
    //无法发送时,返回的异常提示信息  do something
    NSLog(@"error1");
}

-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error
{
    //无法接收时,返回异常提示信息   do something
    NSLog(@"error2");
}

 

 
posted @ 2012-11-16 17:09  qingjoin  阅读(4556)  评论(0编辑  收藏  举报
  Sportica