Swift5:Socket IO集成和发送数据

Swift 5: Socket IO integration and send data

我对 Socket IO 很陌生。我的要求是连接到带有 URL 的套接字,并加入带有一些唯一标识符字符串值(如“join_id”)的特定房间。一旦我成功加入那个房间一旦成功加入那个房间我需要发送一些 JSON 到那个房间并等待确认。

var manager = SocketManager(socketURL: URL(string: myURL)!, config: [ .log(true), .compress ])

    let socket = manager.defaultSocket
    socket.on(clientEvent: .connect){(data,ack) in
        print("connected")
        socket.emit("test", "Hi Server!")
    }

听众是,

    socket.on("testresult") { [weak self] (data,ack) in
        print(data)
        print(data.description)
    }
    socket.connect()

根据服务器团队的要求,我需要通过传递字符串值 (join_id) 来加入房间。一旦我得到成功的确认,我需要发送 JSON 并等待确认确认数据接收。

加入房间特定按下发射数据

self.socketIOClient.emit("join_id", with: "154") /*Like Random id generate*/
let jsonDic = ["room":driver_id,"userId":"\(userID)",
                "quoteId":quote_id,"isRequest":"1"] /* Json Data send to server */
self.socketIOClient.emit("sendRequestToDriver",jsonDic)

获得json回复

let manager:SocketManager!
let socketIOClient: SocketIOClient!
manager = SocketManager(socketURL: URL(string: ServerAPI.SocketURL)!, 
     config: [.log(true), .compress])
socketIOClient = manager.defaultSocket
 self.socketIOClient?.on("orderRequestUpdateByDriver") { ( dataArray, ack) -> Void in
 let dict = dataArray[0] as? NSDictionary ?? [:]
  Print(dict)
}
socketIOClient.on(clientEvent: .error) { (data, eck) in
    print(data)
    print("socket error")
 }
    
socketIOClient.on(clientEvent: .disconnect) { (data, eck) in
    print(data)
    print("socket disconnect")
 }
    
 socketIOClient.on(clientEvent: SocketClientEvent.reconnect) { (data, eck) in
     print(data)
     print("socket reconnect")
 }
socketIOClient.connect()