Socket.io through all pages


#1

Hi all,

I am using socket.io plugin https://github.com/naderio/nativescript-socket.io and it works perfectly fine. I just was wondering if you have any ideas how to implement it through all pages so I don’t have to connect in every page and socket variable would be defined. Any ideas or solutions are highly appreciated. Thanks


#2

Sorry for the hasty and short reply but here goes:

NativeScript modules (files and exported scripts) you require or import are cached in memory, so that if you require a module more than once, you will get the same cached exported functions and classes every time. Keeping that in mind you can implement the connection as a singleton instance, which you just getSocketConnection() for example whenever you want to emit a message to the other end, or change the onRequest callback logic.


#3

@Pete.K thank you for prompt reply. I tired to implement singleton connection like this:

export var socket = SocketIO.connect('https://xxxxxx:3001', <SocketIO.SocketOptions>{
       log: true,
       secure: true,
    query: 'token=xxxxx',        
});
```

but it is only getting connected if I switch off and switch on the app. If I logout and login in it doesn't connect anymore. If I move the same code to components it gets connected multiple times. I need single connection and shared instance afterwards, I just don't know how to implement it. I would be grateful if you could assist with this issue. Thanks

#4

@bachras i use a file “connect.js” with all socketio logic, then require it in home page so that it connects on App start and use observable array in a viewmodel to use in a Chat page, i also require it in my background mode, so in short, one file with all socket logic

 var model=require("./main-view-model");
 var socketIo=require("nativescript-socket.io");
 var Vibrate = require("nativescript-vibrate").Vibrate;
var vibrator = new Vibrate();
 var io= new socketIo.connect('http://192.168.43.79:1100',{'forceNew':true});
 model.connection=io;
 var ObservableArray = require ("data/observable-array");
   model.Chatview=new ObservableArray.ObservableArray([]);
   model.Info=new ObservableArray.ObservableArray([]);
 var username="mmmmi";
   io.on('connect', function(){
    console.log(username+'  is connected  ');
    io.emit('new_client', username,function(data){
        if(data){
           io.emit('check',username ) ;
          }else{
            alert('Error! Use different name') ;
          }
      });
      io.on('new_client', function(data,id) {
        model.ids="";
        model.data="";
        console.log('.......START.......');
        for (var i = 0; i < data.length; i++) {
            model.ids=id[i];
            model.data=data[i];
            Arrz=[{name: model.data,id: model.ids}];
            model.Info=Arrz;
            console.log('names: '+model.data,'id\'s  :'+model.ids);
        }
        console.log('.......FINNISH.......');
      });
 
 exports.sendText=function (args) {
 const data= {text: model.ctext,username: username}
 console.log(model.ctext);
   // io.emit('message',data);
    }
  
  io.on('msg',function(m,u,u2,t,cnt){
        vibrator.vibrate(300,2);
        if(m!=='') {
            for (var i = 0; i < cnt; i++) {
               model.msg=m;
               var dateD=new Date(t);
               timeD=timeAgo(t);
               model.time=timeD;//fecha.format(dateD, ' dddd, H:mm');
                if (u == username) {
                    model.chatClass='msg me';
                    model.name='';
                }
                else{
                   model.chatClass= 'msg them';
                   model.name=u;
                }
                Arr=[{msg: model.msg,chatClass: model.chatClass,time:  model.time,name:  model.name}];
               model.Chatview.push(Arr);
           
    }
        }});
    });

everything is exported usind Model or exports!


#5

If this is the solution, perhaps mark it as such?