如何使用套接字编程将iOS Swift应用程序连接到硬件设备?

时间:2017-06-23 07:08:37

标签: ios swift sockets tcp socket.io

我想使用套接字编程将我的Swift应用程序连接到网络硬件设备。服务器端编程已在使用C语言的硬件设备中完成。如何使用套接字编程连接设备并与之通信?我应该选择哪个库?

1 个答案:

答案 0 :(得分:1)

如果你想做自己的套接字网络,可以使用Swift中的NSStream和CFStream API连接/读/写原始网络套接字。

以下是一些有用的Swift 3片段,用于通过NSStream使用套接字:

var readStream:  Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
var inputStream   : InputStream?    =  nil
var outputStream  : OutputStream?   =  nil

let host : CFString = NSString(string: someHostIPString)
let port : UInt32   = UInt32(somePortNumber)

CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
                                       host,
                                       port,
                                       &readStream,
                                       &writeStream)

inputStream  = readStream!.takeUnretainedValue()
outputStream = writeStream!.takeUnretainedValue()

// the enclosing class should be a StreamDelegate
//   to handle stream open, events, or errors, etc.
inputStream!.delegate   = self
outputStream!.delegate  = self

inputStream.open()
outputStream.open()

// the NSStream delegate callback(s)
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
    var n = 0
    switch (eventCode) {
    ...
    case Stream.Event.hasSpaceAvailable:
    n = self.outputStream.write(someWriteBuffer, maxLength: dataLength) 
    ...
    case Stream.Event.hasBytesAvailable:
    n = self.inputStream.read(someReadBuffer, maxLength: bufferLength)
    ...
    // etc.
    }
}

// etc.

您可能希望使用自己的runloop在自己的线程中运行上面的代码。