socketcluster-client-swift

使用 Swift 编写的 Native iOS/macOS 客户端

概述

此客户端提供以下功能

客户端支持以下平台

安装和使用

CocoaPods

pod 'ScClient'

Swift Package Manager

    dependencies: [
    	// other dependencies 
   	.package(url: "https://github.com/sacOO7/ScClient", from: "2.0.1")
   ]
   targets: [
       .target(
           name: "tool",
           dependencies: [
               "ScClient"
           ])
   ]

描述

通过传递 socketcluster-server 端点的 URL 来创建 scclient 实例

    //Create a client instance
    var client = ScClient(url: "https://:8000/socketcluster/")
    

重要提示:socketcluster 端点的默认 URL 始终为 *ws://somedomainname.com/socketcluster/*。

注册基本监听器

        import Foundation
        import ScClient
        
        var client = ScClient(url: "https://:8000/socketcluster/")

        var onConnect = {
            (client :ScClient) in
            print("Connnected to server")
        }

        var onDisconnect = {
            (client :ScClient, error : Error?) in
                print("Disconnected from server due to ", error?.localizedDescription)
        }

        var onAuthentication = {
            (client :ScClient, isAuthenticated : Bool?) in
            print("Authenticated is ", isAuthenticated)
            startCode(client : client)
        }

        var onSetAuthentication = {
            (client : ScClient, token : String?) in
            print("Token is ", token)
        }
        client.setBasicListener(onConnect: onConnect, onConnectError: nil, onDisconnect: onDisconnect)
        client.setAuthenticationListener(onSetAuthentication: onSetAuthentication, onAuthentication: onAuthentication)
        
        client.connect()
        
        while(true) {
            RunLoop.current.run(until: Date())
            usleep(10)
        }
        
        func startCode(client scclient.Client) {
        	// start writing your code from here
        	// All emit, receive and publish events
        }
        

连接到服务器

    //This will send websocket handshake request to socketcluster-server
    client.connect()

获取连接状态

    //This will send websocket handshake request to socketcluster-server
    var status = client.isConnected()

发送和监听事件

事件发送器

    client.emit(eventName: eventname, data: message as AnyObject)
    
  //client.emit(eventName: "chat", data: "This is my sample message" as AnyObject)
  
    client.emitAck(eventName: "chat", data: "This is my sample message" as AnyObject, ack : {
    	    (eventName : String, error : AnyObject? , data : AnyObject?) in
            print("Got data for eventName ", eventName, " error is ", error, " data is ", data)  
    })
	

事件监听器

收到的对象可以是 String、Boolean、Int 或 Object

    // Receiver code without sending acknowledgement back
    client.on(eventName: "yell", ack: {
    	    (eventName : String, data : AnyObject?) in
            print("Got data for eventName ", eventName, " data is ", data)
    })
    
    // Receiver code with ack
    client.onAck(eventName: "yell", ack: {
            (eventName : String, data : AnyObject?, ack : (AnyObject?, AnyObject?) -> Void) in
            print("Got data for eventName ", eventName, " data is ", data)
            ack("This is error " as AnyObject, "This is data " as AnyObject)
    })
        

通过通道实现发布/订阅

创建通道

    // without acknowledgement
    client.subscribe(channelName: "yell")
    
    //with acknowledgement
    client.subscribeAck(channelName: "yell", ack : {
        (channelName : String, error : AnyObject?, data : AnyObject?) in
        if (error is NSNull) {
            print("Successfully subscribed to channel ", channelName)
        } else {
            print("Got error while subscribing ", error)
        }
    })

在通道上发布事件

	// without acknowledgement
	client.publish(channelName: "yell", data: "I am sending data to yell" as AnyObject)


	// with acknowledgement
	client.publishAck(channelName: "yell", data: "I am sending data to yell" as AnyObject, ack : {
		(channelName : String, error : AnyObject?, data : AnyObject?) in
		if (error is NSNull) {
		     print("Successfully published to channel ", channelName)
		}else {
		     print("Got error while publishing ", error)
		}
	})

监听通道

        client.onChannel(channelName: "yell", ack: {
    		(channelName : String , data : AnyObject?) in
    		print ("Got data for channel", channelName, " object data is ", data)
	})

取消订阅通道

    // without acknowledgement
    client.unsubscribe(channelName: "yell")
    
    //with acknowledgement
    client.unsubscribeAck(channelName: "yell", ack : {
        (channelName : String, error : AnyObject?, data : AnyObject?) in
        if (error is NSNull) {
            print("Successfully unsubscribed to channel ", channelName)
        } else {
            print("Got error while unsubscribing ", error)
        }
    })

禁用 SSL 证书验证

	var client = ScClient(url: "https://:8000/socketcluster/")
        client.disableSSLVerification(true)

自定义队列

当调用委托方法时,可以指定自定义队列。默认情况下,使用 DispatchQueue.main,因此所有委托方法调用都在主线程上运行。重要的是要注意,所有 WebSocket 处理都在后台线程上完成,只有委托方法调用在修改队列时才会更改。实际处理始终在后台线程上,不会暂停您的应用程序。

	var client = ScClient(url: "https://:8000/socketcluster/")
	//create a custom queue
	client.setBackgroundQueue(queueName : "com.example.chatapp")

自定义标头

您还可以使用您自己的自定义标头覆盖默认的 websocket 标头,如下所示

	var request = URLRequest(url: URL(string: "https://:8000/socketcluster/")!)
	request.timeoutInterval = 5
	request.setValue("someother protocols", forHTTPHeaderField: "Sec-WebSocket-Protocol")
	request.setValue("14", forHTTPHeaderField: "Sec-WebSocket-Version")
	request.setValue("Everything is Awesome!", forHTTPHeaderField: "My-Awesome-Header")
	var client = ScClient(URLRequest: request)

自定义 HTTP 方法

您的服务器在连接到 websocket 时可能使用不同的 HTTP 方法

	var request = URLRequest(url: URL(string: "https://:8000/socketcluster/")!)
	request.httpMethod = "POST"
	request.timeoutInterval = 5
	var client = ScClient(URLRequest: request)

协议

如果您需要指定协议,只需将其添加到 init 中

	//chat and superchat are the example protocols here
	var request = URLRequest(url: URL(string: "https://:8000/socketcluster/")!)
	var client = ScClient(URLRequest: request, protocols: ["chat","superchat"])