0
votes

I'm currently having an issue with Node JS, trying to make a very simple chat with session authentification. The authent is ok, but the socket.emit event (server side) is not caught by the socket.on event (client side). Here the code. the file app.js:

app.get('/chat', [requireLogin], require('./lib/chat.js').chat(io));

the file lib/chat.js :

exports.chat = function(io){
    return function(req,res) {
        res.render('chat');

        var ent = require('ent'); // same as htmlentities for PHP

        io.sockets.on('connection', function (socket) {
            var username = ent.encode(socket.handshake.username);

            console.log('first_connection:'+username);
            socket.emit('first_connection', username);

            socket.on('connect_success', function() {
                console.log('connect_success:'+username);
                socket.broadcast.emit('join', username);
            });
        });
    }
};

and the client side:

var sio = io.connect(), socket = sio.socket.of('/chat');

socket.on('first_connection', function (pseudo) {
    console.log('first_connection is caught. Pseudo:'+pseudo);
    document.title = pseudo + ' - ' + document.title;
    socket.emit('connect_success');
});

I got no log on client side, that log on server side:

first_connection:Test
   debug - websocket writing 5:::{"name":"first_connection","args":["Test"]}

[EDIT] Here is the declaration of the IO socket, on my app.js file:

const
    express = require('express'),
    path = require('path'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    fs = require('fs'),
    connect = require('express/node_modules/connect'),
    cookie = require('express/node_modules/cookie')
;
1
NodeJS sockets don't have any of those properties. What library are you presumably using? - OrangeDog
Also, check the Related list for duplicates. - OrangeDog
Thanks for the answer @OrangeDog :) Which property are you talking about ? I edited to add the declaration of the io socket. I have actually no error on the console, nor on server and client side. - Tyrael

1 Answers

0
votes

Ok I went back step by step and redo the same and now it works well ! I think my problem was coming from the installation of a module, cookie, which I forgot.

Thanks anyway ! :)