尝试连接GCDAsyncSocket时,我正在使用以下代码,但我不知道如何获得它以使用SSL。现在,我的代码说它已连接,但几秒钟后将断开连接。套接字从不显示我正在连接。

func connect(){
         bsocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
        bsocket.delegate = self
        do {
            try bsocket.connect(toHost: self.socketHost(), onPort: 443)
        } catch let e {
            NSLog("Error connecting socket: \(e)")
        }
    }

    func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
        let response = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
        print("Received Response: \(response)")

        bsocket.readData(withTimeout: -1.0, tag: 0)
    }


    func disconnect(){
    }



    func socket(_ socket : GCDAsyncSocket, didConnectToHost host:String, port p:UInt16)
    {
        var settings = [AnyHashable: Any](minimumCapacity: 3)
        settings[(kCFStreamSSLPeerName as String)] = self.socketHost()
        //  // Allow self-signed certificates
        settings[(kCFStreamSSLPeerName as String)] = Int(true)
        //  // In fact, don't even validate the certificate chain
        settings[(kCFStreamSSLValidatesCertificateChain as String)] = Int(false)


        print("Connected to \(host) on port \(p).")
        socket.readData(withTimeout: -1.0, tag: 0)
       // sendRequest()
    }

    func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
        NSLog("Socket Disconnected: \(err)")
    }


    func socket(_ sock:GCDAsyncSocket, didAcceptNewSocket newSocket:GCDAsyncSocket)
    {
        NSLog("New socket received: \(newSocket)")
    }

最佳答案

您似乎两次设置了kCFStreamSSLPeerName键的值:

settings[(kCFStreamSSLPeerName as String)] = self.socketHost()
//  // Allow self-signed certificates
settings[(kCFStreamSSLPeerName as String)] = Int(true)


另外,如果您签出https://github.com/robbiehanson/CocoaAsyncSocket/blob/cae3732972501bbb39720be6213f30dc99d9f153/Source/GCD/GCDAsyncSocket.h
您会看到kCFStreamSSLValidatesCertificateChain现在是不可用的密钥,将引发异常。

10-08 17:49