我正在尝试使用网络套接字为我的网站实现聊天.Gobal聊天工作正常。但我不知道如何建立单独的聊天室。我已经制作了数组来存储单独的连接但是。每次打开新连接并添加到阵列时,消息都会全局发送到所有打开的套接字。
在这里添加js代码。
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);
}
});
});
&#13;