有人能告诉我我的代码有什么问题吗?我正在尝试使用socket.io从一个用户向另一个用户发送私人消息。我认为问题出在了
行io.sockets.socket(targetUser).emit('private message', tstamp(), socket.nickname, linkify(msg));
问题是消息没有通过客户端,或者至少没有附加到div。我不确定如何解决问题的确切位置。
相关代码如下 - 我可以添加整个代码,如果这还不够......:
感谢您的帮助。我正在学习node.js和socket.io - 虽然它很慢!
在客户端(发送):
function startPrivateChat(targetUser, sendingUser){
if(targetUser !=sendingUser){
var privateMessage1="starting private chat with " + targetUser + ". My name is " + sendingUser;
var chatBoxId= targetUser + 'ChatBox';
$("#content").append('<div class="chatBox" id="' + chatBoxId + '">' + sendingUser + ', ' + targetUser + '</div>');
$('#' + chatBoxId).append('new private chat');
$('#' + chatBoxId).dialog();
privateMessage(tstamp(), myNick, privateMessage1);
//socket.emit('private message', targetUser, privateMessage1);
clear();
}
}
服务器:
socket.on('private message', function(targetUser,msg) {
io.sockets.socket(targetUser).emit('private message', tstamp(), socket.nickname, linkify(msg));
updateLog('private message', socket.nickname, msg);
});
在客户端(收到):
socket.on('private message', privateMessage);
function privateMessage (msg_time, from, msg) {
$('#chatLogDiv').append($('<p>').append($('<small>').text(msg_time)).append($('<b>').text(from), linkify(msg)));
}
答案 0 :(得分:0)
我得到了这个工作!
在node.js-server上:
socket.on("SendMessage", function (value) {
var userIdToRecieve = theOnlyUserToRecieveString;
io.sockets.emit("SendAMessage", socket.userId, value, userIdToRecieve);
});
在客户端javascript端:
socket.on("SendAMessage", function (userId, value, userIdToRecieve) {
// Write to the conversation window
if (userIdToRecieve == myLocalUserID) {
console.log("I shalleth recieve");
}
});