简体   繁体   English

尝试将 swift 客户端连接到 socket.io 服务器时收到 SSL 错误

[英]Receiving SSL error when trying to connect swift client to socket.io server

I am setting up a Socket.io server in Node.js and client in Swift to implement a real-time chat app.我正在 Node.js 中设置 Socket.io 服务器,在 Swift 中设置客户端来实现实时聊天应用程序。

On the server side, here is the code:在服务器端,代码如下:

const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
const server = app.listen(port, () => {
    console.log(`A Node Js API is listening on port: ${port}`);
});
const io = require("socket.io")(server, {
    rejectUnauthorized: false
});

//set socket.io listeners
io.on('connection', (socket) => {
  console.log('a user connected');

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });

  socket.on("connect_error", (err) => {
    console.log(`connect_error due to ${err.message}`);
    });
});

On the client side, here is the code:在客户端,代码如下:

import SocketIO

class SocketIOManager: NSObject {
    static let sharedInstance = SocketIOManager()
    static let manager = SocketManager(socketURL: URL(string: "https://localhost:8080")!, config: [.log(true), .compress])
    let socket = manager.defaultSocket


    func establishConnection() {
        socket.on("test") { dataArray, ack in
            print(dataArray)
        }
        socket.connect()
    }

    func closeConnection() {
        socket.disconnect()
    }
}

I call establishConnection() in AppDelegate in the applicationDidBecomeActive() method.我在 applicationDidBecomeActive() 方法中调用 AppDelegate 中的建立连接()。 When establishConnection() is getting called, I receive the following SSL Error:当调用建立连接()时,我收到以下 SSL 错误:

LOG SocketManager: Trying to reconnect
LOG SocketIOClient{/}: Handling event: reconnectAttempt with data: [-2]
LOG SocketManager: Scheduling reconnect in 25.7991450561197s
LOG SocketEngine: Starting engine. Server: https://localhost:8080
LOG SocketEngine: Handshaking
LOG SocketEnginePolling: Doing polling GET https://localhost:8080/socket.io/?transport=polling&b64=1 
...
finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." 
UserInfo={NSErrorFailingURLStringKey=https://localhost:8080/socket.io/?transport=polling&b64=1, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, 
_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <A81C6803-9CF8-4930-A6C8-0C633C165D25>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey

I've tried editing Info.plist to change the App Transport Security Settings, but I'm still receiving the error.我已尝试编辑 Info.plist 以更改应用程序传输安全设置,但我仍然收到错误消息。 What could be going wrong?可能出了什么问题?

For anyone struggle that issue, here's a working solution.对于任何为这个问题而苦恼的人,这里有一个可行的解决方案。 you should use the .secure(true), .selfSigned(true) options and the URLAuthenticationChallenge .您应该使用.secure(true), .selfSigned(true)选项和URLAuthenticationChallenge

class ServerLiveDataSocket : NSObject
{
    
    static let shared = ServerLiveDataSocket()
    
    var manager : SocketManager!
    var socket : SocketIOClient!
    
    func initSocketService(symbols : [String], dataPovider : DataProvider)
    {
        manager = SocketManager(socketURL: URL(string: "YOUR_HTTPS_URL_ADDRESS")!, config: [.log(true),
        .compress, .secure(true), .selfSigned(true), .sessionDelegate(self)])
        socket = manager.defaultSocket
        socket.on("users", callback: { data,ack in
            print(data)
        })
        socket.on(clientEvent: .connect) { data, ack in
            self.socket.emit("userNew", userData)
        }
        socket.connect()
    }
    
    
}
extension ServerLiveDataSocket : URLSessionDelegate
{
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM