zoukankan      html  css  js  c++  java
  • 基于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");
    }
    
    
    
     
  • 相关阅读:
    nextLine() 、nextInt()的跳过问题
    Spring事务管理
    常见web错误码
    connect()函数
    int main(int argc,char*argv[])
    cin.getline函数
    TCP数据报结构以及三次握手(图解)
    TCP报文首部
    strtol函数
    MySQL简介
  • 原文地址:https://www.cnblogs.com/qingjoin/p/2773601.html
Copyright © 2011-2022 走看看