While implementing Karconnect in iOS application, I searched my codes to implement Socket-IO in the app, but anyhow the right guidance was lacking. Socket-IO is indeed a huge topic containing various functionalities. I tried my hands on tracking, chatting and video calling functionality of Socket-IO. It really enhances the features of an application and it is user-friendly also.

Let me try to help you to make your development of an app easy.

What is Socket.IO?

Socket.IO enables real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed. As per my experience, I would like to share that steps with to ease your implementation of Socket-IO in your project.

It is a Javascript library for real-time web applications. Socket.IO is built on top of the WebSockets API(Client side) and Node.js. It is one of the most depended-upon library on npm.

Moving to Coding Session

To archive, this Socket.io plays a lead role. Sockets should  need to connect with Node.js(an open-source, cross-platform runtime environment for developing server-side Web applications)

To implement Socket-IO, it is mandatory to setup Node.js, Server.js and index.html.

Steps to install Node.js in system

  1. Open Terminal to install Node.js.  (this is mandatory only if Node.js is not installed)
    1. $ sudo apt-get update
    2. $ sudo apt-get update
    3. $ sudo apt-get install nodejs
    4. $ sudo apt-get install npm
    5. For more information use this link
  2. Socket.IO-objc or  SocketIOClient required Socket.IO of version 0.9.X. If you have the latest version of Socket.IO,an error related to Handshake will prompt.
  3. Create a folder to add Server.js and index.html file. All the Socket.io files will install in this folder.
  4. Go to Terminal,  open the same folder which you created in Step-3
  5. Create Package.json using
    1. $ npm init
    2. $ npm install socket.io@0.9.5 -save
    3. $ npm install express@3.3.5 --save
  6. Create Server.js file and write below code:
  7. var express = require('express');
      var app = express();
      var server = app.listen(3000);
      var io = require('socket.io').listen(server);
    
      server.listen(3000, function () {
     		 console.log('listening on *:3000');
      });
    
      var users = {};
    
      app.get('/', function(req, res){
          res.sendfile('index.html');
      });
    
    
      io.sockets.on('connect', function(socket){
          socket.on("joined", function(username) {
          users[username.email] = socket.id;
                socket.emit('newUserJoined',username);
                console.log(username.email);
         });
         	socket.on('track', function(msg){
                	console.log('message: ' + msg.lat);
      //         io.broadcast.emit('tracked',msg);
               socket.broadcast.emit('tracked', msg);
           });
    });
  8. Create a New File named index.html
  9. <!doctype html>
    <html>
      <head>
        <title>Socket.IO chat</title>
        <style>
          * { margin: 0; padding: 0; box-sizing: border-box; }
          body { font: 13px Helvetica, Arial; }
          form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
          form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
          form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
          #messages { list-style-type: none; margin: 0; padding: 0; }
          #messages li { padding: 5px 10px; }
          #messages li:nth-child(odd) { background: #eee; }
        </style>
      </head>
      <body onload="manageSocket()">
          
        <ul id="messages" style="padding-bottom: 29px; bottom: 16px; margin-bottom: 25px;"></ul>
        <form action="">
          <input id="m" autocomplete="off" /><button>Send</button>
        </form>
            <script src="/socket.io/socket.io.js"></script>
            <script src="http://code.jquery.com/jquery-latest.min.js"></script>
            <script>
    //            var socket = io();
                var person;
                var socket = io.connect('http://192.168.1.11:3000');
                var $chat = $('#tracked');
                function manageSocket() {
                    person = prompt("Please enter your name");
                    if (person != null && person!='') {
                        socket.emit('register', {'email':person});
                    }
                    else{
                        alert('Name is required. Please refresh and enter again.');
                    }
                }
                $('form').submit(function(){
                    if($('#m').val().trim().length>0 ){
                        socket.emit('track', {'to':"pratik",'id':"123",'from':person,'msg':$('#m').val()});
                        $chat.append(person+" - "+ $('#m').val()+"<br />");
                        $('#m').val('');
                        window.scrollTo(0,document.body.scrollHeight);   
                    }else if($('#m').val().length>0){
                        $('#m').val('');
                    }
                    return false;
                });
                
                socket.on('track',function(data){
                    $chat.append(data.from+" - "+ data.msg+"<br />");
                    window.scrollTo(0,document.body.scrollHeight);
                });
                socket.on('joined',function(data){
                    $chat.append(data.email+" has joined <br />");
                });
            </script>
      </body>
    </html>

     

  10. Now, you are ready to run your Socket based program.
  11. Open Terminal and fire $ node Server.js and will respond in Terminal.
  12. Open browser and type localhost:3000 or <your IP>:3000
  13. Run your Project.

Setup with Socket.io-Client-Swift

  1. Set Socket.io-Client for swift using Cocoapods
    • Open Terminal, go to project path.
      • $ open podfile
      • write pod 'Socket.IO-Client-Swift','~> 1.1'
      • $ pod update or $ pod install
      • import Socket_IO_Client_Swift in your ViewController.swift file.
  2. Initialize socket class.
    let socket = SocketIOClient(socketURL: NSURL(string:"<localhost or your server IP>:3000")!, options: [.Log(false)])
  3. Define connectSocket() a function in yours ViewController.swift.
    //MARK: Socket functions
        func connectSocket () {
            socket.connect()
            socket.on("connect") {data, ack in
                print("socket connected.")
                self.enRouteBtn.enabled = true
                self.showRouteBtn.enabled = true
                self.isConnected = true
                self.navigationItem.rightBarButtonItem = nil
            }
            socket.on("close") {data, ack in
                print("socket disconnected.")
                self.isConnected = false
                self.isJoin = false
                self.isTrack = false
    //            self.lastPoint = nil
            }
            socket.onAny {_ in
                //            print("Got event: \($0.event), with items: \($0.items)")
            }
            socket.on("joined") { data, ack in
                print("Joined")
                self.isJoin = true
                self.isTrack = true
                if self.trackFor == "mock" {
                    self.presetTimer?.invalidate()
                    self.presetTimer = nil
                    self.presetTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "changeLocationPositionTimer", userInfo: nil, repeats: true)
                }
            }
            socket.on("leaved") { data, ack in
                print("Left")
                self.isJoin = false
                self.isTrack = false
            }
        }
  4. Call connectSocket() from ViewDidLoad, which will just connect to Server.
  5. To join specific Room, write down below code in your IBAction method.
    self.isTrack = false
    self.isJoin = false
    self.roomName = "MY_ROOM_NAME"
    self.socket.emit("join", [self.roomName])
  6. Send your data to server side by the following code.
    if self.isTrack {
        self.navigationItem.title = "Speed (KM/H): \(20*3.6)"
        let msgob = [
            "lat"  :  String(location.latitude),
            "lng"   : String(location.longitude),
            "speed" : String(20*3.6),
            "room"  : self.roomName,
            "heading" : "25.0"
        ]
        print(msgob)
        self.socket.emit("track", msgob)
    }

     

  7. To leave from Room, call
    if self.isTrack {
        self.isTrack = false
        self.socket.emit("leave", [self.roomName])
        self.locationManager.stopUpdatingLocation()
    }

     

  8. To Close connection between Server and Client, call
    self.socket.emit("close", [self.roomName])

     

     

Hope my content helps you to implement Socket-IO in my app. If any query, feel free to ask me in the below comments. Looking forward for your responses.

Want to work with us? We're hiring!