一.前景
在云硬件设备与手机接入了局域网的情况下,需要将硬件设备扫描展示出,并可选择,与当前手机设备账号进行关联。
二.实现方案流程图如下图所示![局域网下](https://i-blog.csdnimg.cn/blog_migrate/279d191afb02ded2869c3d10e263bc0f.png)
三.方案的代码实现
本次采用 Swift 语言,基于 CocoaAsyncSocket 中的UDPSocket
手机端代码如下:
/// socket实例
var asycUdpSocket: GCDAsyncUdpSocket!
func didload() {
asycUdpSocket = GCDAsyncUdpSocket()
asycUdpSocket.setDelegate(self)
asycUdpSocket.setDelegateQueue(DispatchQueue.main)
/// 尝试绑定 5 次
let _ = udpBindPort(socket: asycUdpSocket, port: 2556, limit: 5)
}
/// 进行端口号绑定
func udpBindPort(socket: GCDAsyncUdpSocket, port: UInt16, limit: Int) -> UInt16 {
if limit == 0 {
return 0
}
var resultError: Error?
do {
try socket.bind(toPort: port)
} catch let error {
resultError = error
}
if resultError != nil {
return udpBindPort(socket: socket, port: port + 1, limit: limit - 1)
}
return port
}
func udpBroadcast() {
do {
/// 开启广播
try asycUdpSocket.enableBroadcast(true)
try asycUdpSocket.beginReceiving()
} catch let error {
print(error)
}
guard let wifiip = wifiIP else {
return
}
let port = asycUdpSocket.localPort()
// 发送消息
let msg = "My IP:Port===\(wifiip):\(port)"
asycUdpSocket.send(msg.data(using: .utf8) ?? Data(), toHost: "255.255.255.255", port: 1221, withTimeout: 5000, tag: 100)
}
/// 获取设备Wifi IP
import SystemConfiguration.CaptiveNetwork
var wifiIP: String? {
var address: String?
var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
guard getifaddrs(&ifaddr) == 0 else {
return nil
}
guard let firstAddr = ifaddr else {
return nil
}
for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
let interface = ifptr.pointee
// Check for IPV4 or IPV6 interface
let addrFamily = interface.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
// Check interface name
let name = String(cString: interface.ifa_name)
if name == "en0" {
// Convert interface address to a human readable string
var addr = interface.ifa_addr.pointee
var hostName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(&addr,socklen_t(interface.ifa_addr.pointee.sa_len), &hostName, socklen_t(hostName.count), nil, socklen_t(0), NI_NUMERICHOST)
address = String(cString: hostName)
}
}
}
freeifaddrs(ifaddr)
return address
}
/// 实现接收到消息的代理
func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
/// 解析接收到的数据信息进行网络请求
}
云硬件设备初始化只需要绑定接收端口,在接收到指定数据包后做出响应通过UDP数据包发送消息,主要代码如下:
/// 接收到消息的代理
func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
var remoteIP = "通过解析指定内容获取"
let remotePort = "通过解析指定内容获取"
// 发送消息
guard let wifiip = wifiIP else {
return
}
let port = asycUdpSocket.localPort()
// 发送消息
let msg = "My IP:Port===\(wifiip):\(port)"
asycUdpSocket.send(msg.data(using: .utf8) ?? Data(), toHost: remoteIP, port: remotePort, withTimeout: 5000, tag: 101)
}