Socket.io some emmits doesn't trigger while others do

550 views Asked by At

I've been trying to get familiarized with socket.io so use it in a real time app. I went through the basic example, a chat room, then I used ngrok to do a test with more than one client and it's all good. Now I'm looking to use TAFFY to save a log of the conversation on deploy it to a new user that connects to it so I added another emmit to send that log, and this particular emmit doesn't seem to ever trigger the on sentence in the client's side.

These are the server instructions

    io.on('connection', function(socket){
  console.log("someone connected");

        var chatLog={log:[]};
    log().each(function (iter){ //this is the taffy var
        chatLog.log.push({"usr":iter.usr,"msg":iter.msg});
    });
    var stringLog=JSON.stringify(chatLog);
    console.log(stringLog);
    socket.emit('cargaLog', stringLog);// THIS is the naughty emmit 

  socket.on('chat message', function(msg){
    var mensaje=JSON.parse(msg);
    log.insert({"usr":mensaje.usr,
                  "msg":mensaje.msg
              });
    io.emit('chat message', mensaje.usr.toUpperCase()+" dice: "+mensaje.msg);
  });
});

Client's side

    $(function () {
      var socket = io();


      socket.on('cargaLog', function(log){
        alert(log); //this never happens
        console.log(log);
      });


      $('form').submit(function(){
        var mensaje=$('#m').val();
        var json='{"usr":"'+person+'","msg":"'+mensaje+'"}';
        socket.emit('chat message', json);
        $('#m').val('');
        return false;
      });


      socket.on('chat message', function(msg){

        var html='<li><img src="defaultUsrImg.png" alt="Usr_img" heigth="40" width="40">'+(msg)+'</li>';
        $('#messages').append(html);
        window.scrollTo(0, document.body.scrollHeight);
      });


      });

I've been staring at this code for a while and none of the solutions that worked with other people work for me (i.e. using io.connect() or io.connect('http://0.0.0.0:8080') on the client's side or having an emmit from the client that asks for the server emmit to be triggered).

Anyone has any idea why this happens? Altenatively, anyone have any idea that could help me troubleshoot this better?

Other details are: Running windows 10 Node version 8.2.1 socket.io version 2.0.3

This how I use the node requires:

var TAFFY = require('taffy');
var express=require('express');
var app = express();
var http = require('http');
var path=require('path');
var port = process.env.PORT || 3000;
var server= http.createServer(app).listen(port);

var io = require('socket.io').listen(server);

var log=TAFFY({"usr":"SERVER",
                  "msg":"WELCOME"
              });

app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');

});

Client html code (only the boddy because mt html includes and it would bee way too long

  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script type="text/javascript" src="./socket.io/socket.io.js"></script>
    <script src="jquery-3.2.1.min.js"></script>
    <!-- <script src="/mensajes.js"></script>  THIS IS THE OLD CODE-->
    <script >
      var person = prompt("Introduce tu nombre o seudonimo", "anon"); //THIS IS THE WORKING CODE

      if(person === null || person===""){
        alert("Necesitas un nombre para participar");
      }
      else{
        $(function () {
          var socket = io();
          socket.emit('ia iege',person);
          socket.on('usrConectado',function(usr){
            var html='<li><h6>'+(usr)+' se ha conectado</h6></li>';
            $('#messages').append(html);
            window.scrollTo(0, document.body.scrollHeight);
          });
          $('form').submit(function(){
            var mensaje=$('#m').val();
            var json='{"usr":"'+person+'","msg":"'+mensaje+'"}';
            socket.emit('chat message', json);
            $('#m').val('');
            return false;
          });
          socket.on('chat message', function(msg){

            var html='<li><img src="https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/419693/pedreiro-1500067445.PNG" alt="Usr_img" heigth="40" width="40">'+(msg)+'</li>';
            $('#messages').append(html);
            window.scrollTo(0, document.body.scrollHeight);
          });
          socket.on('cargaLog', function(log){
            console.log(log);
            var oldLog=JSON.parse(log);
            cargaLog(oldLog);
          });
          });
        function cargaLog(newLog){
            //newLog is an object
            newLog.log.forEach(function(iter){
              var msg=iter.usr.toUpperCase()+' dijo: '+iter.msg;
                 var html='<li><img src="https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/419693/pedreiro-1500067445.PNG" alt="Usr_img" heigth="40" width="40">'+(msg)+'</li>';
            $('#messages').append(html);
            window.scrollTo(0, document.body.scrollHeight);
            });
        }
      }
    </script>
  </body>
3

There are 3 answers

6
jfriend00 On BEST ANSWER

I reduced your code down to just the basics and I'm getting the message just fine that you were having trouble with. Here's the reduced code that works just fine:

Server code:

var express = require('express');
var app = express();
var http = require('http');
var path = require('path');
var port = process.env.PORT || 3000;
var server= http.createServer(app).listen(port);

var io = require('socket.io').listen(server);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/s1.html');

});

io.on('connection', function(socket) {
    console.log("someone connected");

    var chatLog = {log: [{usr: "someuser", msg: "somemsg"}]};
    var stringLog = JSON.stringify(chatLog);
    console.log(stringLog);
    socket.emit('cargaLog', stringLog); // THIS is the naughty emmit 
});

Client Code:

<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script>
function dbg(x) {
    let str = x;
    if (typeof x === "object") {
        str = JSON.stringify(x);
    }
    $("#log").append("<div>" + str + "</div>");
}
$(function() {
    var socket = io();


    socket.on('cargaLog', function(log) {
        dbg(log);
    });

});
</script>
</head>
<body>
Empty Content, waiting for message to arrive.
<div id="log"></div>
</body>
</html>

When I load the page, the browser immediately displays the cargaLog message that you were having trouble with. I would suggest that you backtrack to something super simple like this until you prove it works and then add things back one at a time until you find what is introducing the problem. If this code does not work for you, then you must have something goofed up in your environment and I'd probably do a reinstall of various components (socket.io, node.js, express, etc...).

3
Ginanjar S.B On

I think you can try to look at this repository https://github.com/egin10/socket-chat-example/blob/master/app.js for your server side.

and you can try this one for your client side https://github.com/egin10/socket-chat-example/blob/master/chat.html

Note: Just remember about socket.on(params, callback), it's for fetching data from emmiter, and io.emit(params, obj) on server side is for emmiting data.

so, you must make sure about what is your emmiting to server or client and what's your fetching (socket.on()) from serveror client must have same params.

and you must make sure about your object is var chatLog={log:[]};. if you want to get log, you must do like this chatLog.log.

It's work to me. i hope it can help you.

2
Programmer On

Try

socket.emit('chat message' , { usr: person, msg: mensaje});