在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
有个小需求,app需要监听pc广播的数据: 代码实现思路: 使用三方库:CocoaAsyncSocket 1、开启udp监听: udpSocket.beginReceiving() 2、读取udp的数据,包括对方设备的ip func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?)
实现参考代码: 1、申明变量 var udpSocket : GCDAsyncUdpSocket!
2、根据port端口开启监听 udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main) do{ try udpSocket.bind(toPort: 60001) try udpSocket.beginReceiving() }catch{ print("bind error") }; 其中60001是定义好的端口号
3、实现代理 func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) { //Optional("{\"Port\":61312,\"LPort\":61313,\"HostName\":\"Lucifer-PC\"}")" var hostname = [CChar].init(repeating: 0, count: Int(NI_MAXHOST)) do{ try address.withUnsafeBytes({ (pointer:UnsafePointer<sockaddr>) -> Void in guard getnameinfo(pointer, socklen_t(data.count), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 else{ throw NSError(domain: "domain", code: 0, userInfo: ["error":"unable to get ip address"]) } }) }catch(let error){ print(error.localizedDescription) } var newAddress = String.init(cString: hostname) let addArry = newAddress.components(separatedBy: ":") if addArry.count > 1 { newAddress = addArry[addArry.count-1] } print("IP:\(newAddress)") let dict = data.toDictionary() //data转字典 if let _port = dict["Port"] as? Int,let _lport = dict["LPort"] as? Int, let _name = dict["HostName"] as? String{ //根据广播的信息,构造模型 let model = SocketConnectModel(_ip: newAddress, _port: _port, _lport: _lport, _hostName: _name, _isconnect: false) addWifiArry(model: model) } } 这里解释一下: 一般情况下,我们可能只需要得到广播的内容就足够,也就是上面的 didReceive data: Data,我们直接将data转换我们需要的格式即可。 我这里比较特殊,还需要知道对方设备的ip,所以需要对 fromAddress address: Data,处理。
4、结束监听 udpSocket?.close() 退出页面,或需要结束时,记得调用close方法。
enjoy~ |
请发表评论