我有以下连接TCP套接字的功能(Raspberry Pi上的服务器,我通过接入点直接连接)
func connect (host: String, port: Int) {
Stream.getStreamsToHost(withName: addr, port: port, inputStream: &inputStream, outputStream: &outputStream)
if outputStream != nil && inputStream != nil {
outputStream!.delegate = self
inputStream!.delegate = self
outputStream!.schedule(in: .main, forMode: RunLoopMode.defaultRunLoopMode)
inputStream!.schedule(in: .main, forMode: RunLoopMode.defaultRunLoopMode)
outputStream!.open()
inputStream!.open()
}
}
当我连接到Raspberry Pi的Wifi-Hotspot后,委托方法被调用,我可以开始写数据了:
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if aStream === inputStream {
switch eventCode {
case Stream.Event.errorOccurred:
print("input: ErrorOccurred: \(aStream.streamError?.localizedDescription)")
self.Label.text = "Disconnected"
case Stream.Event.openCompleted:
print("input: OpenCompleted")
case Stream.Event.hasBytesAvailable:
print("input: HasBytesAvailable")
// Here you can `read()` from `inputStream`
default:
break
}
}
else if aStream === outputStream {
switch eventCode {
case Stream.Event.errorOccurred:
print("output: ErrorOccurred: \(aStream.streamError?.localizedDescription)")
self.Label.text = "Disconnected"
case Stream.Event.openCompleted:
print("output: OpenCompleted")
case Stream.Event.hasSpaceAvailable:
// print("output: HasSpaceAvailable")
// Here you can write() to `outputStream`
self.write(f: l)
self.write(f: r)
default:
break
}
}
}
但是当我连接到另一台WiFi时,这种方法不会被调用。 我怎么能检测到这个方法没有被调用,所以我可以提醒用户他没有连接,他应该再次尝试连接?