如何连接到Socket.IO swift?

时间:2018-01-22 09:03:21

标签: swift xcode socket.io

我无法连接到Socket.IO聊天..

import UIKit
import SocketIO

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let manager = SocketManager(socketURL: URL(string: "wss://socket-io-chat.now.sh/socket.io/")!, config: [.log(true), .compress])
        let socket = manager.defaultSocket

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

        socket.on("new message") {data, ack in
            print("new Messages")
        }

        socket.connect()  
    }
}

我正在使用最新的socket.io库,并已在info.plist中添加了应用程序传输。

这是日志所说的内容..

  

2018-01-22 16:56:46.316676 + 0800 ExampleSocket [6963:2231315] LOG SocketEngine:得到的消息:40   2018-01-22 16:56:46.317249 + 0800 ExampleSocket [6963:2231315] LOG SocketEngine:写入poll:有数据:false   2018-01-22 16:56:46.317771 + 0800 ExampleSocket [6963:2231315] LOG SocketEnginePolling:发送轮询:类型:2   2018-01-22 16:56:46.323959 + 0800 ExampleSocket [6963:2231318] TIC读取状态[2:0x0]:1:57   2018-01-22 16:56:46.324082 + 0800 ExampleSocket [6963:2231318] TIC读取状态[2:0x0]:1:57   2018-01-22 16:56:46.330099 + 0800 ExampleSocket [6963:2231315] LOG SocketEnginePolling:创建的POST字符串:1:2   2018-01-22 16:56:46.330615 + 0800 ExampleSocket [6963:2231315] LOG SocketEnginePolling:POSTing   2018-01-22 16:56:46.330744 + 0800 ExampleSocket [6963:2231315] LOG SocketEngine:正在发布引擎

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

var socketClient:SocketIOClient!

if let url = URL(string: "wss://socket-io-chat.now.sh/socket.io/") {
            let socketClient = SocketIOClient(socketURL: url, config: [.log(true),.forcePolling(true)])

            socketClient.connect()
        }


socketClient.onAny { (socEvent) in


if let status =  socEvent.items as? [SocketIO.SocketIOClientStatus] {
            if let first = status.first {
                switch first {
                case .connected:
                    print("Socket: connected")
                    break

                case .disconnected:
                    print("Socket: disconnected")
                    break
                case .notConnected:
                    print("Socket: notConnected")
                    break
                case .connecting:
                    print("Socket: connecting")
                    break
                }
             }
          }
        }