infomation: I have a device on my local network, it is an UDP server and when I send "hello" to it I will get a "how are you" response, but I don't know the IP, so I have to send "hello" to each IP of my local network to find the device.
problem: when I send "hello" to my device,s IP directly, I get the response, but I send "hello" to each IP, I get no response most of the time( sometime I get a response)
some of my code:
//first create a instance of GCDAsyncUdpSocket
udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.global())
do{
log.debug("bind port")
try self.udpSocket?.enableReusePort(true)
try self.udpSocket?.bind(toPort: 0)
udpBindedToPort = true
try self.udpSocket?.beginReceiving()
}catch {
log.error("error")
udpBindedToPort = false
self.delegate?.findDeviceTimeout(0)
return
}
// this does not work
Async.background({[weak self] () in
for i in 1...255 {
let targetIP = ip_sub + ".\(i)"
self?.send(Define.scanDeviceMessage, host: targetIP, tag: Define.scanDeviceTag)
}
})
//this works
Async.background({[weak self] () in
let targetIP = "192.168.0.101"
self?.send(Define.scanDeviceMessage, host: targetIP, tag: Define.scanDeviceTag)
})
//the delegate
@objc func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?
) {
print("UDP接收到数据 : \(String(data:data, encoding: String.Encoding.utf8))")
}
thanks for your help, this drives me crazy, some times it works, but sometime not, and now it never works anymore