飞屏,用手机播放电脑端视频的功能,一般常见于主打VR资源的影音类App。

大体思路:基于UDP协议的广播机制

电脑端不断发送udp广播,广播内容可精简为:端口号;
App用udpSocket扫描,得到对应端口号信息,解析出IP地址,拼接数据,请求数据。

移动端的实现:

1.导入第三方库:CocoaAsyncSocket,引用文件

2.遵守协议:

<GCDAsyncUdpSocketDelegate>

3.初始化对象,启动监听:

_clientSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];   
    NSError * error = nil;
    [_clientSocket setIPv6Enabled:NO]; //每次扫描,你会收到两条信息,IPv4和IPv6的,根据需求做取舍。
    [_clientSocket bindToPort:8080error:&error];// 8080,与电脑端统一的端口号
     if (error) {
        PVRLog(@"clientSocket_error:%@",error);
     } else {
        [_clientSocket beginReceiving:&error];
        PVRLog(@"监听成功开始接收信息");
     }

4.代理回调

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

    NSString *sendMessage = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSString *ip = [GCDAsyncUdpSocket hostFromAddress:address];
    uint16_t port = [GCDAsyncUdpSocket portFromAddress:address];
    PVRLog(@"接收到%@的消息,\n解析到的数据[%@:%d]",sendMessage,ip,port);

}
- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error {
    PVRLog(@"udpSocket关闭withError = %@", error);
}

关于如何使用封装好的工具类,请参考代码