3

我正在尝试在 Swift for iOS 中创建一个套接字服务器应用程序。我发现了这个很好的例子:

    let addr = "127.0.0.1"
    let port = 4000

    var host :NSHost = NSHost(address: addr)
    var inp :NSInputStream?
    var out :NSOutputStream?

    NSStream.getStreamsToHost(host, port: port, inputStream: &inp, outputStream: &out)

    let inputStream = inp!
    let outputStream = out!
    inputStream.open()
    outputStream.open()

    var readByte :UInt8 = 0
    while inputStream.hasBytesAvailable {
        inputStream.read(&readByte, maxLength: 1)
    }

    // buffer is a UInt8 array containing bytes of the string "Jonathan Yaniv.".
    outputStream.write("Hello", maxLength: "Hello".length)

我试图在 XCode 中运行代码,它说 NSHost 不存在。我用谷歌搜索了一下,发现 NSHost 不能用于 iOS。我可以用什么代替?

编辑

我现在使用 Cocoa Async Socket 进行套接字连接。你可以在这里找到它CocoaAsyncScket

4

2 回答 2

2

将 getStreamsToHost 更改为 getStreamsToHostWithName

改变:

NSStream.getStreamsToHost(host, port: port, inputStream: &inp, outputStream: &out)

NSStream.getStreamsToHostWithName(addr, port: port, inputStream: &inp, outputStream: &out)
于 2014-11-17T14:52:23.317 回答
0
var server = "127.0.0.1"
var port = 4000
//var host :NSHost = NSHost(address: server)
var inp :NSInputStream?
var out :NSOutputStream?
NSStream.getStreamsToHostWithName(server, port: port, inputStream: &inp, outputStream: &out)
let inputStream = inp!
let outputStream = out!
inputStream.open()
defer {
    inputStream.close()
}
outputStream.open()
defer {
    outputStream.close()
}
// do stuff here
于 2016-05-02T05:49:34.120 回答