Math Student app

The student.app consumes math functions exposed by MathTutor app.

You need to run the math tutor app [ NodeJS, Python, .NET].If you run multiple instances of math tutor app, dataBridges will automatically load-balance the rpc.function calls.

The student.app uses dataBridges RPC (call-response), functionality.

  • Unary RPC: the client sends a single request and receives a single response.
  • Server streaming RPC: the client sends a single request and in return, the server sends a stream of messages.

The student app will be consuming 2 Unary RPC functions :-> add, multiple. The student app will consume a single server streaming RPC function :-> AllMathFunctions and will receive 4 math operations reply.

We will be using databridges-io/lib.ios.sio.client in student app.

Before trying this sample, follow the Setup and initialization . For more information, see the Channels Pub/Sub API reference documentation.

Download source

Download the math_student_app by clicking on this link

Dependencies

To add databridges-io/lib.ios.sio.client package dependency to your XCode project, select File > Swift Packages > Add Package Dependency and enter repository URLhttps://github.com/databridges-io/lib.ios.sio.client.git. You can also navigate to your target’s General pane, and in the “Frameworks, Libraries, and Embedded Content” section, click the + button, select Add Other, and choose Add Package Dependency.

In XCode's Project navigator, the Swift Package Dependencies section shows the newly added package dependency. Click the disclosure triangle to view the contents of the package as it exists locally on your Mac.

Create a class inside Shared folder and name it as math_student_app, this will create math_student_app.swift file.

Copy paste below code and you are ready to run this example.

/*
    The student.app consumes math functions exposed by MathTutor app.
    The student.app uses dataBridges RPC (call-response), functionality.
    You need to run the math tutor app [ NodeJS, Python, .NET].
    If you run multiple instances of math tutor app, dataBridges will automatically load-balance the rpc.function calls.

    dataBridges supports 2 types of RPC interactions
        Unary RPC: the client sends a request and receives a single response.
        Server streaming RPC: the client sends a request and in return, the receives multiple responses.

    The student app will be consuming 2 Unary RPC functions :-> add, multiple
                            consume a single server streaming RPC function :-> AllMathFunctions
                            and will receive 4 math operations reply.

    We will be using databridges_sio_swift_client in student app.
*/

import Foundation

// Include dataBridges client library package
import databridges_sio_swift_client

public class math_student_app {
    // Initialize dataBridges client
    public var dbridge:databridges_sio_swift_client =  databridges_sio_swift_client()
    public var mlog:logger?=nil
    public var mathFunctions:RpcClient?=nil; 

    init() {}

    public func randomString(of length: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        var s = ""
        for _ in 0 ..< length {
            s.append(letters.randomElement()!)
        }
        return s
    }

    public func Execute() {

        // Replace your application key below, which you have received from dataBridges management portal.
        dbridge.appkey = "____appKey______";

        // Replace your authentication url below, which you have received from dataBridges management portal.
        // example https://endpoint01.databridges.io/client/v1/authenticate
        dbridge.auth_url = "_____URL_____"; 

        try? self.dbridge.connectionstate?.bind("connected", {  (event: Any) in
            print("Connected to dataBridges real-time network !!!: \(String(describing: self.dbridge.sessionid))")
            do{
                // We need to inform dataBridges network that the app want to consume 'mathTutor's functions.
                self.mathFunctions = try self.dbridge.rpc?.connect("MathTutor")
            }catch {
                // Connect errors will be handled here.
                let db = error as?  dBError
                 print("Connecting to MathTutor RPC server faced an exception : \(db?.source) \(db?.code) \(db?.message)")
            }

            if (self.mathFunctions != nil){
                // We will bind to rpc server connection success event. On success, we will call remote functions.
                try? self.mathFunctions?.bind("dbridges:rpc.server.connect.success", {  (event: Any ,  metadata: Any) in
                   print("dataBridges granted access to MathTutor RPC server")

                    if((self.mathFunctions?.isOnline()) != nil){ 
                       var theJSONText:String = ""

                       // Create Random numbers for "a" and "b"
                        let param = ["a": Double.random(in: 0.0...1.0)*100+1 , "b": Double.random(in: 0.0...1.0)*100+1]
                        if let theJSONData = try?  JSONSerialization.data(
                              withJSONObject: param,
                              options: .prettyPrinted
                        ){
                            theJSONText = String(data: theJSONData,
                                                 encoding: .ascii)!
                        }

                        // Unary RPC: The client sends a single request and receives a single response.
                        self.mathFunctions?.call("add", theJSONText, 10000, { (response: Any) in })
                        .done{ (response: Any) in
                            // Last Response will be received here.
                            print("Received response for mathFunctions.call(add) : \(response as! String)")
                        }.catch {(error:Any) in
                            // Catch exception for .call 
                            let db = error as?  dBError
                            print("Error was encountered while executing mathFunctions.call(add) : \(db?.source) \(db?.code) \(db?.message)")
                        }

                        // Unary RPC: The client sends a single request and receives a single response.
                        self.mathFunctions?.call("multiply", theJSONText, 10000, {  (response: Any) in})
                        .done{ (response: Any) in 
                            print("Received response for mathFunctions.call(multiply) : \(response as! String)")
                        }.catch {(error:Any) in
                            // Catch exception for .call
                            let db = error as?  dBError
                            print("Error was encountered while executing mathFunctions.call(multiply) : \(db?.source) \(db?.code) \(db?.message)")
                        }

                        // Server streaming RPC: the client sends a request and in return, the receives multiple responses.
                        self.mathFunctions?.call("AllMathFunction", theJSONText, 10000, {  (response: Any) in
                            print("Received response for mathFunctions.call(AllMathFunction) : \(response as! String)")
                        }).done{ (response: Any) in
                            print("FINAL response for mathFunctions.call(AllMathFunction) : \(response as! String)")
                        }.catch {(error:Any) in
                            // Catch exception for .call
                            let db = error as?  dBError
                            print("Error was encountered while executing mathFunctions.call(AllMathFunction) : \(db?.source) \(db?.code) \(db?.message)")
                        }

                    }
                });

                // Bind to server.connect.fail event to understand if any issues in Math Server Connection.
                try? self.mathFunctions?.bind("dbridges:rpc.server.connect.fail", {(event: Any ,metadata: Any) in
                    let db = event as?  dBError
                    print("MathTutor RPC server faced an issue : \(db?.source) \(db?.code) \(db?.message)")
                });
            }
        });

        // Bind to disconnected event, to get intimation about dataBridges network disconnection.
        try? self.dbridge.connectionstate?.bind("disconnected", {  (event: Any) in
            print("Disconnected from dataBridges real-time network")
        });

        // Connect to dataBridges. If any runtime error it will be caught in catch().
        do{
            try self.dbridge.connect()
        }catch {
            let db = error as?  dBError
            print("dataBridges Connection exception.. \(db?.source) \(db?.code) \(db?.message)")
        }

    }
}

Save your file and build your project in Release or Debug mode to test.