Git Product home page Git Product logo

socketcluster-client-swift's Introduction

socketcluster-client-swift

Native iOS/macOS client written in swift

Overview

This client provides following functionality

  • Easy to setup and use
  • Support for emitting and listening to remote events
  • Pub/sub
  • Authentication (JWT)

Client supports following platforms

  • iOS >= 8.0
  • macOS>= 10.10
  • watchOS >= 2.0
  • tvOS >= 9.0

Installation and Use

pod 'ScClient'

Swift Package Manager

  • To install add this to depedencies section of Package.swift
    dependencies: [
    	// other dependencies 
   	.package(url: "https://github.com/sacOO7/ScClient", from: "2.0.1")
   ]
  • To use the library add this to target dependencies
   targets: [
       .target(
           name: "tool",
           dependencies: [
               "ScClient"
           ])
   ]

Description

Create instance of scclient by passing url of socketcluster-server end-point

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

Important Note : Default url to socketcluster end-point is always ws://somedomainname.com/socketcluster/.

Registering basic listeners

  • Different closure functions are given as an argument to register listeners
  • Example : main.swift
        import Foundation
        import ScClient
        
        var client = ScClient(url: "http://localhost: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
        }
        

Connecting to server

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

Getting connection status

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

Emitting and listening to events

Event emitter

  • eventname is name of event and message can be String, boolean, Int or Object
    client.emit(eventName: eventname, data: message as AnyObject)
    
  //client.emit(eventName: "chat", data: "This is my sample message" as AnyObject)
  
  • To send event with acknowledgement
    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)  
    })
	

Event Listener

  • For listening to events :

The object received can be String, Boolean, Int or 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)
    })
    
  • To send acknowledgement back to server
    // 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)
    })
        

Implementing Pub-Sub via channels

Creating channel

  • For creating and subscribing to channels:
    // 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)
        }
    })

Publishing event on channel

  • For publishing event :
	// 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)
		}
	})

Listening to channel

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

Un-subscribing to channel

    // 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)
        }
    })

Disable SSL Certificate Verification

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

Custom Queue

A custom queue can be specified when delegate methods are called. By default DispatchQueue.main is used, thus making all delegate methods calls run on the main thread. It is important to note that all WebSocket processing is done on a background thread, only the delegate method calls are changed when modifying the queue. The actual processing is always on a background thread and will not pause your app.

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

Custom Headers

You can also override the default websocket headers with your own custom ones like so:

	var request = URLRequest(url: URL(string: "http://localhost: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)

Custom HTTP Method

Your server may use a different HTTP method when connecting to the websocket:

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

Protocols

If you need to specify a protocol, simple add it to the init:

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

socketcluster-client-swift's People

Contributors

sacoo7 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

socketcluster-client-swift's Issues

Cannot install due to error

[!] CocoaPods could not find compatible versions for pod "HandyJSON":
In snapshot (Podfile.lock):
HandyJSON (= 5.0.2)

In Podfile:
HandyJSON

ScClient was resolved to 1.0.5, which depends on
  HandyJSON (~> 1.8.0)

CocoaPods could not find compatible versions for pod "Starscream":
In snapshot (Podfile.lock):
Starscream (= 3.0.6)

In Podfile:
ScClient was resolved to 2.0.1, which depends on
Starscream (~> 3.1.1)

Starscream

HandyJSON and Swift 5

Undefined symbol: _swift_getFieldAt
Please update HandyJSON for compatibility with Swift 5

unsubscribe channel not working in socketcluster

Hi,
@sacOO7

Unsubscribe channel not working on socketcluster.

I have to subscribe 20 channel. Now I want unsubscribe 10 channel. So We are use below code for subscribe.

//  For subscribe 
SoketManager.client.subscribeAck(channelName:"random") { (str, obj1, obj2) in
        print ("Got data for channel", str)
 }

//  Listening to channel                 
SoketManager.client.onChannel(channelName:"random", ack: {
         (channelName : String , data : AnyObject?) in
      print ("Got data for channel", channelName, " object data is ", data ?? "")
 })

We are use below code for unsubscribe.

//  For unsubscribe 
 SoketManager.client.unsubscribeAck(channelName:"random", 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 ?? "")
          }
 })

When I am call "unsubscribeAck" method always get error. Here is error.

{
    message = "Failed to unsubscribe socket from the [object Object] channel - Socket YFaGYE5Tbu1_8we2AAAG tried to unsubscribe from an invalid channel name";
    name = BrokerError;
}

Also I am trying with socketcluster demo as well but It not working for me.
Github link: https://github.com/sacOO7/socketcluster-client-swift

Appreciate your help.

Thanks

How to pass 'socketCluster.authToken' on Socket creation

Hi,
I could not seem to find a way to authenticate with the socket. I know that on the JavaScript client, once I get the token, I need to store it in the local storage:
localStorage.setItem('socketCluster.authToken', token)

I need to send the JWT on every socket request.
Thanks

Update HandyJSON pod dependency

Hi could you please update the pod dependencies so that we can use the newest version of HandyJSON to work with swift 4.1
Thanks

Not Connecting

Hello

I tried to change my server URL and every time i try to connect to our server it show me below error. And i tried our new server URL on web and Android and it's working fine.

Invalid HTTP upgrade code 404

I found you use Starscream 3.1.1 but latest version is 4.0.4

Is this issue because of that ? Looking forward for your help

Thanks
Vishal

How to use in objective-c

Hello

I am trying to use SocketClusteriOS but i found it's very old can not connect to my server.

My question is how can i use this lib to objective-c code ?

Thanks
Vishal

Socket getting disconnected too often

Socket is getting disconnected too often and giving this error:
The operation couldn’t be completed. (Starscream.WSError error 1.

can you please help? Its critical.

Listener cannot remove handlers for events

class Listener has a property dictionary of event names to closures. We are able to register new listeners, but we can never remove them. Please add a new method so we can remove them.

class Listener {

removeListener(eventName: String) {
    self.onListener[eventName] = nil
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.