iOS

来源:互联网 发布:刘嘉玲面膜淘宝店 编辑:程序博客网 时间:2024/04/27 23:27

Socket 通信中,TCP/UDP,接着UDP的方法:

- (void)initSendSocket

{

    if (!_sendTextUdpSocket) {

        _sendTextUdpSocket = [[GCDAsyncUdpSocketalloc] initWithDelegate:selfdelegateQueue:dispatch_get_main_queue()];

    }

    

    NSError *error =nil;

    

    if (![_sendTextUdpSocketbindToPort:PORTerror:&error])

    {

        NSLog(@"Error binding(_sendTextUdpSocket):%@", error);

        return;

    }

    if (![_sendTextUdpSocketbeginReceiving:&error])

    {

        NSLog(@"Error receiving(_sendTextUdpSocket): %@", error);

        return;

    }

    

    NSLog(@"_sendTextUdpSocket ready!");

    

    

}

//2、实现代理方法

//发送成功回调方法

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag

{

    NSLog(@"did Send Data");

}

//发送失败回调方法

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error

{

    NSLog(@"did Not Send Data");

}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext

{

    //接收到的数据

    NSString *msg = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];

    NSLog(@"%@", msg);

    

}

//3、发送数据

- (void)sendMsg:(NSString *)msg

{

    NSData *data = [msgdataUsingEncoding:NSUTF8StringEncoding];

   

    [_sendTextUdpSocketsendData:data toHost:HOSTport:PORTwithTimeout:-1tag:0x100];

    

}





0 0