Mahesh Narla
Mahesh Narla

Reputation: 352

ios how to implement SocketIO in iOS

I have a Server Address: http://someaddress.com/ by using SocketIO iOS library to connect to the above address with the correct protocol and namespace.

Socket Namespace: “/random”

Socket Event for random number: “capture”

This server uses SocketIO to send the randomly generated numbers every 4 seconds over the namespace “/random” with the event “capture”. How to access above address using SocketIO library. Thanks in advance.

Upvotes: 1

Views: 591

Answers (1)

Hrishikesh
Hrishikesh

Reputation: 526

enum Socket: String{

case serverURL = "YOUR_SERVER_URL"
case namespace = "NAMESPACE NAME"
case eventName = "EVENT NAME"

}

/// Represents actual socket object with server url and namespace.

var socket: SocketIOClient = SocketIOClient(socketURL: NSURL(string: Socket.serverURL.rawValue)! as URL, config: [.nsp(Socket.namespace.rawValue)])

override init() {
    super.init()
}

/**
 This function used to establish connection with server.
 - Parameter: nil.
 - Returns: nil.
 */
func establishConnection() {
    socket.connect()
}

/**
 This function used to fetch next number from server.
 - Parameter: nil.
 - Returns: nil.
 */
func nextNumberFromServer(){
    socket.on(Socket.eventName.rawValue) {data, ack in
        if let number = data[0] as? NSNumber {
            print(number)
        }
    }
}

/**
 This function used to close connection with server.
 - Parameter: nil.
 - Returns: nil.
 */
func closeConnection() {
    socket.disconnect()
}

Upvotes: 4

Related Questions