3
votes

I'm trying to create a real time chat using socket.io. I have everything working except the auto update when someone else posts a new message. I believe something is wrong with my io.sockets.emit & socket.on('message', getMessages());

I've tried various emit and socket.on combinations. I'm using express 4.16.4 and socket.io 2.2.0.

This is my index.js

var express = require('express');
var router = express.Router();
var app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);

//Render Chat
router.get('/Chat', function(req, res, next) {
    ChatData.find({},(err, messages)=> {
    var chatmessages = messages;    
    res.render('Chat', {messages: chatmessages, csrfvalid: req.session.csrf, csrfToken: req.csrfToken(), loginerrors: req.session.loginerrors, success: req.session.success, errors: req.session.errors, user: req.session.user });
    req.session.errors = null;
    req.session.loginerrors = null;
    req.session.csrfvalid = null;
    })
});

//GET Messages
router.get('/messages', (req, res) => {
  ChatData.find({},(err, messages)=> {
    res.send(messages);
  })
})

//POST chat
router.post('/chat', function(req, res, next) {
    var item = {
        name: req.body.name,
        message: req.body.message
    };  
    var data = new ChatData(item);
    data.save(function(err) {
        if(err){
            console.log(err);
            return;         
        }
        io.sockets.emit("message", req.body);
        res.send({});       
    })  
});

this is my chat client javascript

<script>
   var socket = io('http://MY_IP:3000', { transport : ['websocket'] });
    $(() => {
        $("#send").click(()=>{
            sendMessage({name: $("#name").val(), message: $("#message").val(), _csrf: $("#csrf").val()});
            document.getElementById('name').value = "";
            document.getElementById('message').value = "";
        })
        //getMessages()
    })
    socket.on('message', getMessages());

    function addMessages(message){
        $("#messages").append('<b>', message.name, '</b> : ' , message.message,' <a href="delete?_id='+message._id+'">Delete</a><br><br>')
    }
    function getMessages(){
      $.get('http://MY_IP:3000/messages', (data) => {
        data.forEach(addMessages);
      })
    }
    function sendMessage(message){
      $.post('http://MY_IP:3000/chat', message)
    }
</script>

When I post a chat from another client, my computer should automatically load the new message at the bottom of the div. I currently have to reload the page. I believe the error is in the io.sockets.emit or the socket.on.

in my server.js I use the below code, which works.

//Socket
io.on('connection', () => { console.log('a user is connected') });
2

2 Answers

0
votes

Try this modification in your client side code.

      function getMessages(){
          $.get('http://MY_IP:3000/messages', (data) => {
             $.each(data,(i,v)=>{
                 addMessages(v)
             })
          })
       }
0
votes

It looks like you're calling getMessages() when specifying that function as the handler for the client sockets message event:

/* This is incorrect, as you're calling getMessages() immediately,
rather than specifying it as a function handler to be called when 
the "message" event occurs */
socket.on('message', getMessages());

Removing the () from getMessages() on that line should resolve the problem:

/* Corrected code */
socket.on('message', getMessages);

/* Add another call to getMessages() to fetch messages automatically on start */
getMessages()

To ensure messages are fetched automatically when your client app starts, you can add a second call to getMessages() directly after socket.on(...) as shown above.