使用UDP方式 与iOS端App通讯

  • 首先需要安装一个TCP&UDP测试工具
  • 连接类型选择UDP
  • 目标IP 设置手机的IP, 端口8888 (这个端口在App端用来绑定)
  • 指定端口, 是App向回发信息所需要的端口, 具体设置如下图所示
创建连接

接下来为减少代码的键入, 我直接使用CocoaAsyncSocket这个三方库,作为中间媒介完成整个过程

{
      GCDAsyncUdpSocket *udpSocket; // 定义一个socket的对象 签订代理 GCDAsyncUdpSocketDelegate
}

麦 2017/7/20 17:05:40
    /*************** UDP ***********************/
    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    NSError *error = nil;
    // 绑定端口
    [udpSocket bindToPort:8888 error:&error];
    // 启用广播
    [udpSocket enableBroadcast:YES error:&error];
    
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"启用失败"];
    }else {
        NSLog(@"%@", [udpSocket localHost]);
        // 开始接收消息
        [udpSocket beginReceiving:&error];

    }
    /*************** UDP ***********************/

#pragma mark - GCDAsyncUdpSocketDelegate
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(nullable id)filterContext {

    NSLog(@"success");
    NSString *ip = [GCDAsyncUdpSocket hostFromAddress:address];
    NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"收到响应 %@ %@", ip, s);
    [sock receiveOnce:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        uint16_t port = 9999;
        [self sendBackToHost:ip port:port withMessage:s];
    });
}
- (void)sendBackToHost:(NSString *)ip port:(uint16_t)port withMessage:(NSString *)s{
    // 回一个 hello summerxx too
    char *str = "hello summerxx too" ;
    NSData *data = [NSData dataWithBytes:str length:strlen(str)];
    [udpSocket sendData:data toHost:ip port:port withTimeout:0.1 tag:200];
}
收到信息
发回一条信息

注 如果是多个Socket对象 在回调中可以用目标端口进行区分获取数据即可
sock.localPort 来取得目标端口.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容