Cocoaasyncsocket problem, GCDAsyncSocket Connection problem

964 Views Asked by At

why when trying to connect when the server does not respond "try" shows that it is connected?

I need to check the connection status. Every time, despite the timeout setting, it shows that it is connected ...

My code:

        socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
        do {
            try socket?.connect(toHost: "192.168.1.1", onPort: 5000, withTimeout: 5)
            print ("connect")

        }catch  {
            print("socket error")

        }

And one more question,

i create two socket on the same port:

socket1.connect(toHost: "192.168.1.1", onPort: 5000, withTimeout: 5)
socket2.connect(toHost: "192.168.1.1", onPort: 5000, withTimeout: 5)

in func:

func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
 ...
}

How to detect which socket (socket1 or socket2 ) has been disconnected?

2

There are 2 best solutions below

6
Michael Dautermann On

GCDAsyncSocket does have delegate methods (and in your code example above, you do set the delegate to self). So implement a tiny function with the Swift equivalent of this function:

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port

Something like:

socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
do {
    // I don't think socket should be optional here...
    try socket.connect(toHost: "192.168.1.1", onPort: 5000, withTimeout: 5)

} catch  {
    print("socket error")

}

func socket(socket : GCDAsyncSocket, didConnectToHost host:String, port p:UInt16)
{
    print("connected to \(host) & \(port)")
}

where you've moved your "print("connected!")" there. If the socket connected, you'll see the print appear in your console.

1
JoeGalind On

I would assign a value to the "tag" property on each socket, and then, on the delegate, compare the socket.tag parameter to figure out which one disconnected.

socket1.tag = 1
socket2.tag = 2


func socket(socket : GCDAsyncSocket, didConnectToHost host:String, port p:UInt16)
{
    if (socket.tag==1) {
       print("Socket 1 disconnected")
    } 
}