目前我正在开发一个程序,在该程序中我使用 NSNetService 类连接两个 IOS 设备。我能够连接两个设备,但我不知道如何使用 getInoutStream 函数发送数据。有没有小伙伴可以帮帮我。
问问题
361 次
1 回答
1
为什么不使用multipeer?对于您正在尝试做的事情,这是一个更简单的解决方案。NSNetService 也有一些已知的错误。但是,您可以通过在 NSNetService 上设置 Bonjour 连接在两者之间发送数据。getInputStream 方法需要 UnsafeMutablePointer 类型的参数:
public func getInputStream(inputStream: UnsafeMutablePointer<NSInputStream?>, outputStream: UnsafeMutablePointer<NSOutputStream?>) -> Bool
var inputStream : NSInputStream?
var outputStream : NSOutputStream?
let success = service.getInputStream(&inputStream, outputStream: &outputStream)
然后只需使用内存流写入数据,它将被传递到侦听器端口。
这是完成的代码:
此函数在 127.0.0.1 上启动连接
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()
这是针对流 IO 的:
func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) { //This is the stream IO function. It allows RW of the stream
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
default:
// default code here
break
}
于 2016-04-29T08:16:33.893 回答