1

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>
Luis L
  • 13
  • 5
  • We need some help with what troubleshooting you've already done. Are you getting the server-side console message from: `console.log("someone connected");` Are you seeing this log msg: `console.log(stringLog);`? Are they what you expect them to be? I'm wondering if something before `socket.emit('cargaLog', stringLog);` is throwing an exception so it never gets to that line of code. – jfriend00 Jul 27 '17 at 22:04
  • You should be asking an actual question. – Difster Jul 27 '17 at 22:09
  • Yes @jfriend00 The logs show exactly what theyre supposed to show when someone connects and the TAFFY var is saving what it has to. Also the server keeps running just fine, and people can still connect through NGROK – Luis L Jul 27 '17 at 22:15
  • I don't see why it wouldn't work. On a guess that there could be a timing issue related to sending a message on a "just connected" socket, can you try changing this on the server: `socket.emit('cargaLog', stringLog);` to this: `setTimeout(function() {socket.emit('cargaLog', stringLog)}, 500);` as an experiment. – jfriend00 Jul 28 '17 at 00:46
  • It didn't change a thing, I even tried it on ubuntu to make sure it wasn't some windows 10 shenanigans, and its the same problem. I'm gonna back peddal my way to the requires and see if maybe the way im executing the services is messing something up. Thanks for the help friend – Luis L Jul 28 '17 at 02:19
  • I added how I do the requires I reworked them to made them look less messy, the behaviour is still the same @jfriend00 – Luis L Jul 28 '17 at 16:58

3 Answers3

0

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...).

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • This helped a lot, it was the client's side that was at fault, for some reason I need to have the script right in the html file so all emmits work properly, do you have any idea why this is jfriend? Thank you for all your help – Luis L Jul 28 '17 at 18:04
  • @LuisL - If you show me the whole client-side page as it was with the problem, I can probably spot the problem. I don't understand from your description and the limited code you've shown. – jfriend00 Jul 28 '17 at 18:12
  • I added the snippet I think that the relevant part. – Luis L Jul 28 '17 at 18:37
  • @LuisL - FYI, `"./socket.io/socket.io.js"` should be `"/socket.io/socket.io.js"` with no leading period. The socket.io server is looking for an absolute path, not a relative path. Probably won't make a difference on a top level page, but could in other pages. Using `./` is a problem waiting to happen. – jfriend00 Jul 28 '17 at 18:42
  • After changing the socket io reference it works the same way, only straight JS on the HTML file works with all emmits. I'm thinking that if it was a scope problem it would stop working entirely, could it be the socket.io version? – Luis L Jul 28 '17 at 18:59
  • @LuisL - Then, that's probably because your JS files weren't being loaded properly or you had some variables in a private scope that external JS can't access. There's no reason that JS in a web page can't be in an external script file and has to be directly in the page. – jfriend00 Jul 28 '17 at 19:02
-1

Try

socket.emit('chat message' , { usr: person, msg: mensaje});
Programmer
  • 75
  • 1
  • 6
  • I don't think this is the `.emit()` the OP is asking about. I think they're asking about this one: `socket.emit('cargaLog', stringLog);`. – jfriend00 Jul 27 '17 at 22:05
  • Indeed the basic chat emits work fine is the one called 'cargaLog' that never shows up – Luis L Jul 27 '17 at 22:07
-1

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.

  • Yes, since this is a basic app I opted to pass every parameter as string, thats why I stringify my chatLog object and on the client side I simply print it, as any other string. If it all worked correctly I would simply parse the JSON sting back to an object on the client's side – Luis L Jul 27 '17 at 22:30
  • `var json='{"usr":"'+person+'","msg":"'+mensaje+'"}';` where is `person` variable ? have you defined it ? – Ginanjar S.B Jul 28 '17 at 03:17
  • Yes, it's a variable that is obtained by a prompt at the start of the script, the messages work as they should the problem is that emmit called 'cargaLog' – Luis L Jul 28 '17 at 03:24