Ad

Socket.io Doesn't Understand The Usernames

I try to add a Chatbox to my youtube web app. When you enter the app, there is an alert which wants a username from you to tell people who you are. Lets say mine is name1. When I write something on the chat it shows like name1: bla bla.

But when another person join the chat, lets say name2. I see his/her messages as name1 and he/she sees my messages as name2.

I've tried to tell socket.io the diffrences between but apparently I failed..

This is the app.js:

// Socket setup
io.on('connection', function(socket) { 

  // username
  socket.on('new user', function(username) {
    socket.username = username;
    io.emit('new user', username);
    console.log(username + ' connected');
    io.emit('connection2', "Welcome to Ömür's Chatbox " + username);  
    socket.on('disconnect', function() {
      console.log(username + ' disconnected');
    });
  });

  // chatbox
  socket.on('chat message', function(msg){
    console.log('message: ' + msg);
    io.emit('chat message', msg);
  });

  // User connections
  console.log('User ' + socket.id + ' Connected');
  socket.on('disconnect', function() {
    console.log('User ' + socket.id + ' Disconnected');
  });  
});

This is the script in the main ejs:

var socket = io();
var username = prompt("What's your username?");

socket.emit('new user', username);

$('form').submit(function() {
  socket.emit('chat message', $('#m').val());
  $('#m').val('');
  return false;
});

socket.on('chat message', function(msg) {     
  var li = $("<li></li>");
  var span = $("<span></span>").css('color', getUsernameColor(username));
  span.addClass("userNameSpan");

  $('#messages').append($(li).text(msg));
  $(li).prepend($(span).text(username));       
});

socket.on('connection2', function(msg) {
  $('#messages').append($('<li style="font-style:italic;">').text(msg));
});  

You can check the full code from here

Ad

Answer

Currently the other Peer doesn't know the username of the sender.

Include it in the Message like this:

$('form').submit(function() {
  let message = {
    username: username,
    payload: $('#m').val()
  }
  socket.emit('chat message', message);
  return false;
});

socket.on('chat message', function(message) {
  let {payload, username} = message;
  var li = $("<li></li>");
  var span = $("<span></span>").css('color', getUsernameColor(username));
  span.addClass("userNameSpan");

  $('#messages').append($(li).text(payload));
  $(li).prepend($(span).text(username));
}
Ad
source: stackoverflow.com
Ad