我想建立一個連接到TCP服務器,與NSInputStream
和NSOutputStream
。 HasBytesAvailable
或HasSpaceAvailable
- 事件永遠不會收到。所以我不知道套接字是否真的被設置了?NSInputStream/NSOutputStream不開放
在這種特殊情況下,我可以訪問服務器,並且實際上可以看到它建立了連接,所以我試圖在收到HasSpaceAvailable
事件之前寫入數據並且它工作正常!
但由於HasBytesAvailable
-event從來沒有觸發我不知道什麼時候從流中讀取。
雖然我已經閱讀了大部分類似的帖子,並嘗試了很多,但沒有運氣。
如果任何人都能看到我錯過的東西,那對我很有幫助! :)
下面是我班上的相關代碼:
class TCPConnection : NSObject, NSStreamDelegate {
private var host: String
private var port: Int
private var inputStream: NSInputStream?
private var outputStream: NSOutputStream?
private var readyToWrite = true
init(host: String, port: Int) {
self.host = host
self.port = port
super.init()
NSStream.getStreamsToHostWithName(self.host, port: self.port, inputStream: &inputStream, outputStream: &outputStream)
inputStream!.delegate = self
outputStream!.delegate = self
inputStream!.scheduleInRunLoop(.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.scheduleInRunLoop(.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream!.open()
outputStream!.open()
}
func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
if (aStream == inputStream) {
print("event received: inputStream")
switch eventCode {
case NSStreamEvent.ErrorOccurred:
print("ErrorOccurred: \(aStream.streamError?.description)")
break
case NSStreamEvent.EndEncountered:
print("EndEncountered: \(aStream.streamError?.description)")
break
case NSStreamEvent.HasBytesAvailable:
print("HasBytesAvailable")
break
case NSStreamEvent.None:
print("None")
break
case NSStreamEvent.OpenCompleted:
print("opened!")
break
default:
print("default")
}
} else if aStream == outputStream {
print("event received: outputStream")
switch eventCode {
case NSStreamEvent.ErrorOccurred:
print("ErrorOccurred: \(aStream.streamError?.description)")
break
case NSStreamEvent.EndEncountered:
print("EndEncountered: \(aStream.streamError?.description)")
break
case NSStreamEvent.HasSpaceAvailable:
print("HasSpaceAvailable")
break
case NSStreamEvent.None:
print("None")
break
case NSStreamEvent.OpenCompleted:
print("opened!")
break
default:
print("default")
}
} else {
print("another stream?")
}
}
}
這對我的作品。你在使用操場嗎?你需要'NSRunLoop.mainRunLoop()。run()'。 – jtbandes
你在使用什麼類型的服務器?在某些情況下,你將需要包括'/ N' ** **或'/ N/r',另闢蹊徑,TCP是第三方API,例如[CocoaAsyncSocket(https://github.com/robbiehanson/CocoaAsyncSocket) – Xrait