broadcast to room works on every second connection in socket.io with android












0















I created socket io server using nodejs and from android connected to the server.



I am using io. socket: socket. io-client: 1.0.0 library for android.



The problem was when I try to send message when open app it works. But when I reconnect socket I it not works. Just when second reconnection it works. Every second connection. Previously I tried to add users to client variable, then emit to socketid. But now I am using the rooms.



I think socket io server store old room, and for second connection it works properly



How can I refresh rooms before broadcast or broadcast last updated rooms?



server.js



module.exports = (httpsServer) => {
const io = require('socket.io')(httpsServer, {
log: false,
cookie: false,
multiplex: false
});
io.set({
transports: ['websocket', 'polling']
});
io.on('connection', (socket) => {

ocket.on('join', (id) => {
console.log(id + " joined");
socket.join(id);
});
socket.on('disconnect', (id) => {
console.log(id + " leaved");
socket.leave(id);
});

socket.on('messageToUser', (endUserId, msg) => {
console.log("admin broadcast to: " + endUserId);
socket.broadcast.to(endUserId).emit('inbox', {
senderId: '1',
endUser: endUserId,
message: msg
});
socket.emit('inbox', {
senderId: '1',
endUser: endUserId,
message: msg
});
});
});
};


App.java



public class App extends Application {

private Socket mSocket;
{
try {
IO.Options opts = new IO.Options();
opts.secure = true;
opts.transports = new String{WebSocket.NAME};
opts.reconnection = true;
opts.forceNew = true;
opts.multiplex = false;
mSocket = IO.socket("...",opts);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}

public Socket getSocket() {
return mSocket;
}
}


ChatActivity.java



    App app = (App) getApplication();
mSocket = app.getSocket();
mSocket.on(Socket.EVENT_CONNECT,onConnect);
mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on("inbox", inbox);
mSocket.connect();
sendButton.setOnClickListener(v -> {
if (!mSocket.connected()) return;
if(!messageEditText.getText().toString().trim().isEmpty()){
mSocket.emit("messageToUser", endUserId, messageEditText.getText().toString());
messageEditText.setText("");
}
});

private Emitter.Listener onConnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(!isConnected) {
mSocket.emit("join", userInfoSharedP.getUserId());
isConnected = true;
}
}
});
}
};

...









share|improve this question





























    0















    I created socket io server using nodejs and from android connected to the server.



    I am using io. socket: socket. io-client: 1.0.0 library for android.



    The problem was when I try to send message when open app it works. But when I reconnect socket I it not works. Just when second reconnection it works. Every second connection. Previously I tried to add users to client variable, then emit to socketid. But now I am using the rooms.



    I think socket io server store old room, and for second connection it works properly



    How can I refresh rooms before broadcast or broadcast last updated rooms?



    server.js



    module.exports = (httpsServer) => {
    const io = require('socket.io')(httpsServer, {
    log: false,
    cookie: false,
    multiplex: false
    });
    io.set({
    transports: ['websocket', 'polling']
    });
    io.on('connection', (socket) => {

    ocket.on('join', (id) => {
    console.log(id + " joined");
    socket.join(id);
    });
    socket.on('disconnect', (id) => {
    console.log(id + " leaved");
    socket.leave(id);
    });

    socket.on('messageToUser', (endUserId, msg) => {
    console.log("admin broadcast to: " + endUserId);
    socket.broadcast.to(endUserId).emit('inbox', {
    senderId: '1',
    endUser: endUserId,
    message: msg
    });
    socket.emit('inbox', {
    senderId: '1',
    endUser: endUserId,
    message: msg
    });
    });
    });
    };


    App.java



    public class App extends Application {

    private Socket mSocket;
    {
    try {
    IO.Options opts = new IO.Options();
    opts.secure = true;
    opts.transports = new String{WebSocket.NAME};
    opts.reconnection = true;
    opts.forceNew = true;
    opts.multiplex = false;
    mSocket = IO.socket("...",opts);
    } catch (URISyntaxException e) {
    throw new RuntimeException(e);
    }
    }

    public Socket getSocket() {
    return mSocket;
    }
    }


    ChatActivity.java



        App app = (App) getApplication();
    mSocket = app.getSocket();
    mSocket.on(Socket.EVENT_CONNECT,onConnect);
    mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
    mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
    mSocket.on("inbox", inbox);
    mSocket.connect();
    sendButton.setOnClickListener(v -> {
    if (!mSocket.connected()) return;
    if(!messageEditText.getText().toString().trim().isEmpty()){
    mSocket.emit("messageToUser", endUserId, messageEditText.getText().toString());
    messageEditText.setText("");
    }
    });

    private Emitter.Listener onConnect = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
    runOnUiThread(new Runnable() {
    @Override
    public void run() {
    if(!isConnected) {
    mSocket.emit("join", userInfoSharedP.getUserId());
    isConnected = true;
    }
    }
    });
    }
    };

    ...









    share|improve this question



























      0












      0








      0








      I created socket io server using nodejs and from android connected to the server.



      I am using io. socket: socket. io-client: 1.0.0 library for android.



      The problem was when I try to send message when open app it works. But when I reconnect socket I it not works. Just when second reconnection it works. Every second connection. Previously I tried to add users to client variable, then emit to socketid. But now I am using the rooms.



      I think socket io server store old room, and for second connection it works properly



      How can I refresh rooms before broadcast or broadcast last updated rooms?



      server.js



      module.exports = (httpsServer) => {
      const io = require('socket.io')(httpsServer, {
      log: false,
      cookie: false,
      multiplex: false
      });
      io.set({
      transports: ['websocket', 'polling']
      });
      io.on('connection', (socket) => {

      ocket.on('join', (id) => {
      console.log(id + " joined");
      socket.join(id);
      });
      socket.on('disconnect', (id) => {
      console.log(id + " leaved");
      socket.leave(id);
      });

      socket.on('messageToUser', (endUserId, msg) => {
      console.log("admin broadcast to: " + endUserId);
      socket.broadcast.to(endUserId).emit('inbox', {
      senderId: '1',
      endUser: endUserId,
      message: msg
      });
      socket.emit('inbox', {
      senderId: '1',
      endUser: endUserId,
      message: msg
      });
      });
      });
      };


      App.java



      public class App extends Application {

      private Socket mSocket;
      {
      try {
      IO.Options opts = new IO.Options();
      opts.secure = true;
      opts.transports = new String{WebSocket.NAME};
      opts.reconnection = true;
      opts.forceNew = true;
      opts.multiplex = false;
      mSocket = IO.socket("...",opts);
      } catch (URISyntaxException e) {
      throw new RuntimeException(e);
      }
      }

      public Socket getSocket() {
      return mSocket;
      }
      }


      ChatActivity.java



          App app = (App) getApplication();
      mSocket = app.getSocket();
      mSocket.on(Socket.EVENT_CONNECT,onConnect);
      mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
      mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
      mSocket.on("inbox", inbox);
      mSocket.connect();
      sendButton.setOnClickListener(v -> {
      if (!mSocket.connected()) return;
      if(!messageEditText.getText().toString().trim().isEmpty()){
      mSocket.emit("messageToUser", endUserId, messageEditText.getText().toString());
      messageEditText.setText("");
      }
      });

      private Emitter.Listener onConnect = new Emitter.Listener() {
      @Override
      public void call(Object... args) {
      runOnUiThread(new Runnable() {
      @Override
      public void run() {
      if(!isConnected) {
      mSocket.emit("join", userInfoSharedP.getUserId());
      isConnected = true;
      }
      }
      });
      }
      };

      ...









      share|improve this question
















      I created socket io server using nodejs and from android connected to the server.



      I am using io. socket: socket. io-client: 1.0.0 library for android.



      The problem was when I try to send message when open app it works. But when I reconnect socket I it not works. Just when second reconnection it works. Every second connection. Previously I tried to add users to client variable, then emit to socketid. But now I am using the rooms.



      I think socket io server store old room, and for second connection it works properly



      How can I refresh rooms before broadcast or broadcast last updated rooms?



      server.js



      module.exports = (httpsServer) => {
      const io = require('socket.io')(httpsServer, {
      log: false,
      cookie: false,
      multiplex: false
      });
      io.set({
      transports: ['websocket', 'polling']
      });
      io.on('connection', (socket) => {

      ocket.on('join', (id) => {
      console.log(id + " joined");
      socket.join(id);
      });
      socket.on('disconnect', (id) => {
      console.log(id + " leaved");
      socket.leave(id);
      });

      socket.on('messageToUser', (endUserId, msg) => {
      console.log("admin broadcast to: " + endUserId);
      socket.broadcast.to(endUserId).emit('inbox', {
      senderId: '1',
      endUser: endUserId,
      message: msg
      });
      socket.emit('inbox', {
      senderId: '1',
      endUser: endUserId,
      message: msg
      });
      });
      });
      };


      App.java



      public class App extends Application {

      private Socket mSocket;
      {
      try {
      IO.Options opts = new IO.Options();
      opts.secure = true;
      opts.transports = new String{WebSocket.NAME};
      opts.reconnection = true;
      opts.forceNew = true;
      opts.multiplex = false;
      mSocket = IO.socket("...",opts);
      } catch (URISyntaxException e) {
      throw new RuntimeException(e);
      }
      }

      public Socket getSocket() {
      return mSocket;
      }
      }


      ChatActivity.java



          App app = (App) getApplication();
      mSocket = app.getSocket();
      mSocket.on(Socket.EVENT_CONNECT,onConnect);
      mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
      mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
      mSocket.on("inbox", inbox);
      mSocket.connect();
      sendButton.setOnClickListener(v -> {
      if (!mSocket.connected()) return;
      if(!messageEditText.getText().toString().trim().isEmpty()){
      mSocket.emit("messageToUser", endUserId, messageEditText.getText().toString());
      messageEditText.setText("");
      }
      });

      private Emitter.Listener onConnect = new Emitter.Listener() {
      @Override
      public void call(Object... args) {
      runOnUiThread(new Runnable() {
      @Override
      public void run() {
      if(!isConnected) {
      mSocket.emit("join", userInfoSharedP.getUserId());
      isConnected = true;
      }
      }
      });
      }
      };

      ...






      android node.js sockets socket.io






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 28 '18 at 18:01







      Benfactor

















      asked Dec 28 '18 at 17:47









      BenfactorBenfactor

      4910




      4910
























          2 Answers
          2






          active

          oldest

          votes


















          0














          you need background or foreground service for ChatActivity or at least asynctask , also u can use global public variable for socket instance this is needed for properly running






          share|improve this answer
























          • Can you give examples ?

            – Benfactor
            Dec 29 '18 at 12:23



















          0














          I found a problem. I am using pm2 process manager. And I run PM2 with its built in load balancer. Something like this:



          pm2 start server -i 2


          And when I stop pm2 and start own node server, it works properly. I think problem in load balancing with 2 core. And when I connect socket every second connection emit works. It is because of dividing processes into two.



          Firstly install redis



          # on mac
          brew install redis
          sudo brew services start redis


          Then install the socket.io redis adapter in project



          npm i socket.io-redis --save


          Finally,



          const sockets = require('socket.io')
          const redis = require('socket.io-redis')

          const bindListeners = (io) => {
          io.on('connection', (socket) => {
          console.log(`${socket.id} connected`)
          })
          }

          module.exports = (server) => {
          const io = sockets(server, {
          transports: [ 'websocket', 'polling' ]
          })
          // Add the redis adapter
          io.adapter(redis({ host: 'localhost', port: 6379 }))
          bindListeners(io)
          }





          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53962390%2fbroadcast-to-room-works-on-every-second-connection-in-socket-io-with-android%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            you need background or foreground service for ChatActivity or at least asynctask , also u can use global public variable for socket instance this is needed for properly running






            share|improve this answer
























            • Can you give examples ?

              – Benfactor
              Dec 29 '18 at 12:23
















            0














            you need background or foreground service for ChatActivity or at least asynctask , also u can use global public variable for socket instance this is needed for properly running






            share|improve this answer
























            • Can you give examples ?

              – Benfactor
              Dec 29 '18 at 12:23














            0












            0








            0







            you need background or foreground service for ChatActivity or at least asynctask , also u can use global public variable for socket instance this is needed for properly running






            share|improve this answer













            you need background or foreground service for ChatActivity or at least asynctask , also u can use global public variable for socket instance this is needed for properly running







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 29 '18 at 10:27









            ServooServoo

            1




            1













            • Can you give examples ?

              – Benfactor
              Dec 29 '18 at 12:23



















            • Can you give examples ?

              – Benfactor
              Dec 29 '18 at 12:23

















            Can you give examples ?

            – Benfactor
            Dec 29 '18 at 12:23





            Can you give examples ?

            – Benfactor
            Dec 29 '18 at 12:23













            0














            I found a problem. I am using pm2 process manager. And I run PM2 with its built in load balancer. Something like this:



            pm2 start server -i 2


            And when I stop pm2 and start own node server, it works properly. I think problem in load balancing with 2 core. And when I connect socket every second connection emit works. It is because of dividing processes into two.



            Firstly install redis



            # on mac
            brew install redis
            sudo brew services start redis


            Then install the socket.io redis adapter in project



            npm i socket.io-redis --save


            Finally,



            const sockets = require('socket.io')
            const redis = require('socket.io-redis')

            const bindListeners = (io) => {
            io.on('connection', (socket) => {
            console.log(`${socket.id} connected`)
            })
            }

            module.exports = (server) => {
            const io = sockets(server, {
            transports: [ 'websocket', 'polling' ]
            })
            // Add the redis adapter
            io.adapter(redis({ host: 'localhost', port: 6379 }))
            bindListeners(io)
            }





            share|improve this answer






























              0














              I found a problem. I am using pm2 process manager. And I run PM2 with its built in load balancer. Something like this:



              pm2 start server -i 2


              And when I stop pm2 and start own node server, it works properly. I think problem in load balancing with 2 core. And when I connect socket every second connection emit works. It is because of dividing processes into two.



              Firstly install redis



              # on mac
              brew install redis
              sudo brew services start redis


              Then install the socket.io redis adapter in project



              npm i socket.io-redis --save


              Finally,



              const sockets = require('socket.io')
              const redis = require('socket.io-redis')

              const bindListeners = (io) => {
              io.on('connection', (socket) => {
              console.log(`${socket.id} connected`)
              })
              }

              module.exports = (server) => {
              const io = sockets(server, {
              transports: [ 'websocket', 'polling' ]
              })
              // Add the redis adapter
              io.adapter(redis({ host: 'localhost', port: 6379 }))
              bindListeners(io)
              }





              share|improve this answer




























                0












                0








                0







                I found a problem. I am using pm2 process manager. And I run PM2 with its built in load balancer. Something like this:



                pm2 start server -i 2


                And when I stop pm2 and start own node server, it works properly. I think problem in load balancing with 2 core. And when I connect socket every second connection emit works. It is because of dividing processes into two.



                Firstly install redis



                # on mac
                brew install redis
                sudo brew services start redis


                Then install the socket.io redis adapter in project



                npm i socket.io-redis --save


                Finally,



                const sockets = require('socket.io')
                const redis = require('socket.io-redis')

                const bindListeners = (io) => {
                io.on('connection', (socket) => {
                console.log(`${socket.id} connected`)
                })
                }

                module.exports = (server) => {
                const io = sockets(server, {
                transports: [ 'websocket', 'polling' ]
                })
                // Add the redis adapter
                io.adapter(redis({ host: 'localhost', port: 6379 }))
                bindListeners(io)
                }





                share|improve this answer















                I found a problem. I am using pm2 process manager. And I run PM2 with its built in load balancer. Something like this:



                pm2 start server -i 2


                And when I stop pm2 and start own node server, it works properly. I think problem in load balancing with 2 core. And when I connect socket every second connection emit works. It is because of dividing processes into two.



                Firstly install redis



                # on mac
                brew install redis
                sudo brew services start redis


                Then install the socket.io redis adapter in project



                npm i socket.io-redis --save


                Finally,



                const sockets = require('socket.io')
                const redis = require('socket.io-redis')

                const bindListeners = (io) => {
                io.on('connection', (socket) => {
                console.log(`${socket.id} connected`)
                })
                }

                module.exports = (server) => {
                const io = sockets(server, {
                transports: [ 'websocket', 'polling' ]
                })
                // Add the redis adapter
                io.adapter(redis({ host: 'localhost', port: 6379 }))
                bindListeners(io)
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 30 '18 at 19:49

























                answered Dec 30 '18 at 18:13









                BenfactorBenfactor

                4910




                4910






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53962390%2fbroadcast-to-room-works-on-every-second-connection-in-socket-io-with-android%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Mossoró

                    Error while reading .h5 file using the rhdf5 package in R

                    Pushsharp Apns notification error: 'InvalidToken'