1

I am trying to implement a chat for my web site using web sockets.Gobal chatting works fine. But i don't know how to make separate chat rooms. I've made and array to store separate connections but. When each time i open a new connection and added to the array the messages are send global to all opened sockets.

Adding js code here.

var sockets = []; //array that stores connections


function addText(e) {
  console.log(activeChatWindow + " " + e);
  if (isMyMsg(e)) {
    $("#" + activeChatWindow).append($("<p class=\"Msg\" ></p>").text(e));
  } else {
    $("#" + activeChatWindow).append(
      $("<p class=\"Msg\" id=\"recvMsg\"></p>").text(e));
  }
  $("#userInput").val("");

}

function sendText(user) {

  var msg = formatText();
  msg += $("#userInput").val();
  console.log(sockets[user]);
  sockets[user].send(msg);

}

function formatText() {
  var date = new Date();

  var text = u;
  text += "[" + date.getDate() + "." + (date.getMonth() + 1) + "." + date.getFullYear() + ":" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "]: ";
  return text;

}

function isMyMsg(e) {
  var i = e.indexOf("[");
  var user = e.slice(0, i);

  if (user == u)
    return true;

  return false;

}





function openNewConnection(user) {
  sockets[user] = new WebSocket("ws://localhost:8080/socket");
  console.log(sockets[user]);
  sockets[user].onopen = function(event) {

    console.log('Connection open!');

  };

  sockets[user].onmessage = function(event) {
    console.log(event.data + " " + user);
    addText(event.data);
  };

}

$(window).load(


  function() {



    for (var friend in myFriends) {
      loadFriend(myFriends[friend], friend);
      console.log("hello");

    };
    $("#send").click(function(e) {
      sendText(activeChatWindow);

    });

    $("#userInput").keypress(function(e) {

      if (e.which == 13) {
        e.preventDefault();
        sendText(activeChatWindow);
      }

    });



  });
Jozef Chocholacek
  • 2,874
  • 2
  • 20
  • 25
Niinle
  • 121
  • 9
  • possible duplicate of [node.js multi room chat example](http://stackoverflow.com/questions/3409589/node-js-multi-room-chat-example) – vidriduch Jul 06 '15 at 10:02
  • yes. Problem is that project specifications do not allow me to use node.js. Kind of frustrating. – Niinle Jul 06 '15 at 12:26

0 Answers0