在Swift中从NSInputStream接收数据 [英] Receiving Data from NSInputStream in Swift
问题描述
我尝试在Swift中使用NSOutputStream和NSInputStream发送和接收数据.数据发送工作正常,但是我对接收有一些疑问.
I try to send and receive data with NSOutputStream and NSInputStream in Swift. The sending of data is working well, but i have some questions about the receiving.
我找到了一种尝试处理NSStreamEvent的解决方案.
I found a solution with handling the NSStreamEvent, which i have tried.
首先,我要初始化连接的功能:
First of all my function for initializing the connection:
func initNetworkCommunication(){
var host : CFString = "127.0.0.1"
var port : UInt32 = 7001
var readstream : Unmanaged<CFReadStream>?
var writestream : Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, &readstream, &writestream)
inputstream = readstream!.takeRetainedValue()
outputstream = writestream!.takeRetainedValue()
inputstream.delegate = self
outputstream.delegate = self
inputstream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputstream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputstream.open()
outputstream.open()
}
这部分正在工作.我已经将委托设置为self,所以我应该能够处理此类中的NSStreamEvents.
This part is working. I have set the delegates to self, so i should be able to handle the NSStreamEvents in this class.
func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
switch (eventCode){
case NSStreamEvent.OpenCompleted:
NSLog("Stream opened")
break
case NSStreamEvent.HasBytesAvailable:
NSLog("HasBytesAvailable")
break
case NSStreamEvent.ErrorOccurred:
NSLog("ErrorOccurred")
break
case NSStreamEvent.EndEncountered:
NSLog("EndEncountered")
break
default:
NSLog("unknown.")
}
}
据我了解,每次到达某些数据时,它应该打印"HasBytesAvaible",但它打印未知".每次.所以我玩了一下,它可以解决这个问题:
In my understanding everytime when some data arrives, it should print "HasBytesAvaible", but it printed "unknown." everytime. So i played around a bit and it worked with this:
func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
var buffer = [UInt8](count: 4096, repeatedValue: 0)
while (inputstream.hasBytesAvailable){
let result: Int = inputstream.read(&buffer, maxLength: buffer.count)
}
switch (eventCode){
case NSStreamEvent.OpenCompleted:
NSLog("Stream opened")
break
case NSStreamEvent.HasBytesAvailable:
NSLog("HasBytesAvailable")
var output = NSString(bytes: &buffer, length: buffer.count, encoding: NSUTF8StringEncoding)
NSLog("output: %@", output)
receiveMessage(output) //only adds the message to an array
break
case NSStreamEvent.ErrorOccurred:
NSLog("ErrorOccurred")
break
case NSStreamEvent.EndEncountered:
NSLog("EndEncountered")
break
default:
NSLog("unknown.")
}
}
它正以这种方式工作,但是我想问你这是否是正确的方式?此时的最佳实践是什么?
It's working this way, but i wanted to ask you whether this is the right way ? What is the best practice at this point ?
更新 几周前,我再次进行了研究,找出了自己的错误.这是工作代码.
UPDATE I worked on it again a few weeks ago and figured out my mistakes. So here is the working code.
func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
switch (eventCode){
case NSStreamEvent.ErrorOccurred:
NSLog("ErrorOccurred")
break
case NSStreamEvent.EndEncountered:
NSLog("EndEncountered")
break
case NSStreamEvent.None:
NSLog("None")
break
case NSStreamEvent.HasBytesAvailable:
NSLog("HasBytesAvaible")
var buffer = [UInt8](count: 4096, repeatedValue: 0)
if ( aStream == inputstream){
while (inputstream.hasBytesAvailable){
var len = inputstream.read(&buffer, maxLength: buffer.count)
if(len > 0){
var output = NSString(bytes: &buffer, length: buffer.count, encoding: NSUTF8StringEncoding)
if (output != ""){
NSLog("server said: %@", output!)
}
}
}
}
break
case NSStreamEvent.allZeros:
NSLog("allZeros")
break
case NSStreamEvent.OpenCompleted:
NSLog("OpenCompleted")
break
case NSStreamEvent.HasSpaceAvailable:
NSLog("HasSpaceAvailable")
break
}
推荐答案
您遗漏了事件hasSpaceAvailable
,我希望该事件在显示未知"时发生.告诉您已经准备好接收更多数据.
You're missing the event hasSpaceAvailable
, which I expect is occurring when it says "unknown". It's telling you that it is ready to receive more data.
通常,我会避免在switch语句中为枚举使用default
,因为编译器会在您错过某些内容时告诉您.
Generally, I avoid using default
in switch statements for enums, since the compiler will tell you when you've missed something.
这篇关于在Swift中从NSInputStream接收数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!