我已经使用此实现了聊天应用程序(https://github.com/jdutheil/nodePHP),but现在我想要两个用户之间的私聊,但我不知道如何实现它。请帮我解决以下问题。
当用户登录他的帐户时,它将列出(使用带有朋友姓名的超链接)他的朋友,如Facebook,其中有一个唯一的ID关联,点击每个项目,它会打开一个带有文本框和按钮的新聊天页面并启动chat.Here是代码
开始-聊天与 - friends.php
<?php
//uniqueid of the friend
$id=$_GET['id'];
?>
<form class="form-inline" id="messageForm">
<input id="messageInput" type="text" class="input-xxlarge" placeHolder="Message" />
<input type="submit" class="btn btn-primary" value="Send" />
</form>
chatclient.js
$( "#messageForm" ).submit( function() {
var msg = $( "#messageInput" ).val();
socket.emit('join', {message:msg} );
$( "#messageInput" ).val('');
});
chatServer.js**
socket.on('join', function( data ) {
io.sockets.emit('new_msg'+data.to,{message:data.message});
});
答案 0 :(得分:3)
你好,这可能对你有帮助
var users = {};
var sockets = {};
io.sockets.on('connection', function(socket) {
// Register your client with the server, providing your username
socket.on('init', function(username) {
users[username] = socket.id; // Store a reference to your socket ID
sockets[socket.id] = { username : username, socket : socket }; // Store a reference to your socket
});
// Private message is sent from client with username of person you want to 'private message'
socket.on('private message', function(to, message) {
// Lookup the socket of the user you want to private message, and send them your message
sockets[users[to]].emit(
'message',
{
message : message,
from : sockets[socket.id].username
}
);
});
});