How to install sockets in cordova both backend and frontend

Date : 04/09/2019

Introduction

Generally Sockets are used for realtime update bidirectionally between client and server. The following will describe how to configure in cordova framework. Sockets are pipeline connection will instantly reflect change other side when connected. You just only need to listen on for that event emission. This article is quick setup for cordova.

Server Setup

We are using node js in backend server. All node js project will have main file that will include all the modules we have included in the project and will also initiate server. For convention, generally it will be named as app.js or index.js.

We will install and initiate sockets in that file. Make sure you have sockets in node modules directory in your project.

else run one following command to reinstalled all needed modules.

npm install

The code snippet for initiating sockets are

const express = require('express');
const app = express();
const http =require('http').createServer(app)
const io = require('socket.io')(http);
io.sockets.on('connection', function(socket){    
    console.log('User is connected');
    socket.emit('text', 'wow. such event. very real time.');
});

The snippet will do the magic. The setup guide on official website has outdated setup. I am doing all the setup process in my local machine for front end and backend.

Client Setup

Before we start the setup process, we assume you have setup cordova project.

Firstly, declare the socket in html file you want to use. There is also some other way to declare socket in fornt end.

http://192.168.0.7:3000/socket.io/socket.io.js
Finally, setup socket listener when the project ready with event listener callback in your js file.
var socket = io.connect("http://192.168.43.248:3000");
socket.on("connect", function(){
console.log("socket connected");
socket.on("text", function(txt){
console.log(txt);
});
});

That's it. The above IP is my private IP. find and use your own IP.
When you compile the project, you will see the log 'wow. such event. very real time.'
Thank you for visiting pheonixsolutions.com. If you find anything incomplete in this article, Please drop a comment.

To keep it live, share it with your friends.

Leave a Reply