让GCDAsyncSocket在swift中期望SSL

时间:2016-10-26 18:43:21

标签: ios swift sockets gcdasyncsocket

我在尝试连接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)")
    }

1 个答案:

答案 0 :(得分:0)

您好像是在两次设置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现在是一个不可用的密钥,并将抛出异常。