Swift 使用 GCDAsyncSocket 创建套接字客户端

Swift create socket client with GCDAsyncSocket

如何使用 swift 语言创建带有 GCDAsyncSocket 的套接字客户端。 我使用以下代码:

class MySocketClient: GCDAsyncSocketDelegate{
let addr = "192.168.131.218"
let port :UInt16 = 8000
var inp :NSInputStream?
var out :NSOutputStream?
var bsocket: GCDAsyncSocket!
var err :NSError?

func initClient(name: String) ->String{
    bsocket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
    return "init result:"+name
}

func connect(){
    if(!bsocket.connectToHost(addr, onPort: port, error: nil)){
        println("Error.")
    }else{
        println("Connecting...")

    }
}
}

但是很奇怪,

的结果

bsocket.connectToHost(addr, onPort: port, error: nil) always return true.

无论我更改ip地址还是端口都不可用

为什么?创建套接字客户端并将其用于 receive/send 数据到服务器的正确方法是什么?

connectToHost returns 正确,因为连接尝试已成功启动。

建立连接后,将调用委托方法socket:didConnectToHost:port:

来自 connectToHost 的文档:

This method will return NO if an error is detected, and set the error pointer (if one was given). Possible errors would be a nil host, invalid interface, or socket is already connected.

If no errors are detected, this method will start a background connect operation and immediately return YES. The delegate callbacks are used to notify you when the socket connects, or if the host was unreachable.