CocoaAsyncSocket使用笔记之GCDAsyncUdpSocket


先去github的网站下载最新的包,然后先看看介绍。

https://github.com/robbiehanson/CocoaAsyncSocket/wiki/Intro_GCDAsyncSocket

网上很多都是老版本的帖子。官方已经推出了GCDAsyncSocket来代替以前老的AsyncSocket。


1、引入GCDAsyncSocket所需要的框架,CFNetwork和security这两个

2、下面是我的Udp的客户端。


/**

 *  定义

 */

@property (strong, nonatomic) GCDAsyncUdpSocket *myGcdUdpSocket;


// 第二步初始化 Setup our socket.


- (void)setupSocket

{

//要发送的到的服务器IP地址

    self.networkIP = @"172.16.36.9";

//服务器接收端口号码

    portField.text = @"9999";

//监听服务器返回信息端口号

    self.portFieldListen.text = @"9998";

    /**

     *  zhaojian

     *  组播地址默认是224.0.0.2,如果大于224.0.0.2的话,就要设置GCDAsyncUdpSocketTTL

     */

    self.myGcdUdpSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

    NSError *error2;

    //int listenPort = [portField.text intValue];

    int listenPort = [self.portFieldListen.text intValue];

    NSLog(@"listenPort%d", listenPort);

    [_myGcdUdpSocket bindToPort:listenPort error:&error2];

    if (nil != error2)

    {

        NSLog(@"Failed%@", [error2 description]);

    }

    [_myGcdUdpSocket enableBroadcast:YES error:&error2];

    if (nil != error2)

    {

        NSLog(@"Failed%@", [error2 description]);

    }

    //组播

    [_myGcdUdpSocket joinMulticastGroup:@"224.0.0.2" error:&error2];

    if (nil != error2)

    {

        NSLog(@"Failed%@", [error2 description]);

    }

    [_myGcdUdpSocket beginReceiving:&error2];

    if (nil != error2)

    {

        NSLog(@"Failed%@", [error2 description]);

    }

}


-(void)dealloc

{

    if (_myGcdUdpSocket)

    {

        [_myGcdUdpSocket close];

    }

}


以下为发送和接收UDP信息


- (IBAction)send:(id)sender

{

    NSString *host = self.networkIP;

    

if ([host length] == 0)

{

[self logError:@"Address required"];

return;

}

int port = [portField.text intValue];

if (port <= 0 || port > 65535)

{

[self logError:@"Valid port required"];

return;

}

    

NSString *msg = messageField.text;

if ([msg length] == 0)

{

[self logError:@"Message required"];

return;

}

    NSData *dataHead = [NSData dataWithBytes:byte length:sizeof(byte)];

    NSData *dataBody = [msg dataUsingEncoding:NSUTF8StringEncoding];

    NSData *dataCheck = [NSData dataWithBytes:byteCheck length:sizeof(byteCheck)];


    NSMutableData *totalData = [[NSMutableData alloc]init];

    [totalData appendData:dataHead];

    [totalData appendData:dataBody];

    [totalData appendData:dataCheck];

    


    NSData *data = [totalData mutableCopy];

    Byte *sendByte = (Byte *)[data bytes];

    

    NSString *hexStr = @"";

    for (int i=0; i<[data length]; i++)

    {

        //16进制数

        NSString *newHexStr = [NSString stringWithFormat:@"%x", sendByte[i]&0xff];

        if ([newHexStr length] == 1)

        {

            hexStr = [NSString stringWithFormat:@"%@ 0%@",hexStr, newHexStr];

        }

        else

        {

            hexStr = [NSString stringWithFormat:@"%@ %@",hexStr, newHexStr];

        }

    }

    NSLog(@"sendByte16进制数为:%@", hexStr);

    


[udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:tag];

[self logMessage:FORMAT(@"已发送 (%i): %@ : %@ ", (int)tag, msg, host)];

tag++;

}


- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error

{

    NSLog(@"---upSocketDidClose--%@", [error description]);

}


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

{

// You could add checks here

     NSLog(@"---didSendDataWithTag--");

}


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

{

// You could add checks here

     NSLog(@"---didNotSendDataWithTag--");

}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data

                                               fromAddress:(NSData *)address

                                         withFilterContext:(id)filterContext

{

    NSLog(@"-----didReceiveData-----");

NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

if (msg)

{

[self logMessage:FORMAT(@"已经接收: %@", msg)];

}

else

{

NSString *host = nil;

uint16_t port = 0;

[GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];

[self logInfo:FORMAT(@"已经接收: Unknown message from: %@:%hu", host, port)];

}

}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值