如何连接到socketIO

时间:2019-05-05 01:29:26

标签: ios swift socket.io

我已经连接到socketIO,但仍然出错

为此,我创建了一个socketIo管理器

SocketIOManager类:NSObject {

static let sharedInstance = SocketIOManager()


func establishConnection() {
    socket.connect()

}

func closeConnection() {
    socket.disconnect()
}
func join(nickname: String) {



    socket.emit("join", nickname)
}



func exitChatWithNickname(nickname: String, completionHandler: () -> Void) {
    socket.emit("userdisconnect", nickname)
    completionHandler()
}


func sendMessage(message: String, withNickname nickname: String) {
    socket.emit("messagedetection", nickname, message)
}


func getChatMessage(completionHandler: @escaping (_ messageInfo: Message) -> Void) {
    socket.on("message") { (dataArray, socketAck) -> Void in
        var message = Message()

        let eventDataTemp = dataArray[0] as? [String: Any]
        //let eventData = eventDataTemp![0] as? Dictionary<String, String>;
        print(eventDataTemp)
        message.idUser = eventDataTemp?["senderNickname"] as! String
        message.message = eventDataTemp?["message"] as! String
        completionHandler(message)
    }
}


private func listenForOtherMessages() {
    socket.on("userjoinedthechat") { (dataArray, socketAck) -> Void in
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "userWasConnectedNotification"), object: dataArray[0] as! [String: AnyObject])
    }
}

}

这是我的错误 LOG SocketIOClient {/}:处理事件:数据错误:[“未连接时尝试发射”]

2 个答案:

答案 0 :(得分:0)

尝试一下 在全局添加

let manager = SocketManager(socketURL: URL(string: "http://localhost:8080")!, config: [.log(true), .compress])
let socket = manager.defaultSocket

调用此方法

import SocketIO


func callSocket()
{
   socket.on(clientEvent: .connect) {data, ack in
       print("socket connected")
   }

   socket.on("currentAmount") {data, ack in
       guard let cur = data[0] as? Double else { return }

       socket.emitWithAck("canUpdate", cur).timingOut(after: 0) {data in
           socket.emit("update", ["amount": cur + 2.50])
       }

       ack.with("Got your currentAmount", "dude")
   }

   socket.connect()
}

访问:https://github.com/socketio/socket.io-client-swift

答案 1 :(得分:0)

您的错误清楚地表明您的应用正在尝试emit while its not connected to socket。在发出任何发射之前,需要确保已建立与套接字的连接。 通常,您希望在应用程序开始运行时连接到套接字,而在应用程序关闭或进入后台时关闭连接。

这就是我在应用程序中实现SocketIO的方式。

步骤1:创建一个名为SocketManager.swift的套接字管理器文件,并添加以下代码。

import SocketIO

class SocketIOManager: NSObject {
    static let sharedInstance = SocketIOManager()

    let manager = SocketManager(socketURL: URL(string: "YOUR_SOCKET_URL")!, config: [.log(true), .connectParams([])

    var socket: SocketIOClient!

    override init() {
    super.init()

        socket = manager.defaultSocket

        //Listener to capture any message that your server emits for "emitMessage" key. You can add multiple listeners to capture various emits from your server.
        socket.on("emitMessage") { (data, ack) in
            print("Socket Ack: \(ack)")
            print("Emitted Data: \(data)")
            //Do something with the data you got back from your server.
        }
    }

    //Function for your app to emit some information to your server.
    func emit(message: [String: Any]){
        print("Sending Message: \([message])")
        socket.emit("sendMessage", with: [message])
    }

    //Function to establish the socket connection with your server. Generally you want to call this method from your `Appdelegate` in the `applicationDidBecomeActive` method.
    func establishConnection() {
        socket.connect()
        print("Connected to Socket !")
    }

    //Function to close established socket connection. Call this method from `applicationDidEnterBackground` in your `Appdelegate` method.
    func closeConnection() {
        socket.disconnect()
        print("Disconnected from Socket !")
    }
}

步骤2:在您的AppDelegate.swift文件中添加以下内容。

func applicationDidEnterBackground(_ application: UIApplication) {
    SocketIOManager.sharedInstance.closeConnection()
}

func applicationDidBecomeActive(_ application: UIApplication) {
    SocketIOManager.sharedInstance.establishConnection()
}

第3步:无论何时要向服务器发出信号,都可以在应用程序中的任何位置进行。

SocketIOManager.sharedInstance.emit(message: "message": "This is a test message")