iosswiftsocketsgcdasyncsocket

Swift create socket client with GCDAsyncSocket


How to create a socket client with GCDAsyncSocket using swift langauge. I use following code:

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...")

    }
}
}

But it is strange, the result of

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

No matter I change the ip address or port which are not available.

Why? And what is the right way to create a socket client, and use it to receive/send data to server?


Solution

  • connectToHost returns true because the connection attempt has started successfully.

    When the connection is made, the delegate method socket:didConnectToHost:port: will be called.

    From the documentation for 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.