How to implement private chat in php using nodejs and socket.io

I have been using a chat app using this ( https://github.com/jdutheil/nodePHP ),but now I want a private chat between two users, but I don't know how to bring it up. Please help me to solve the following problem.

When the user logs into his account, he will list (using friends' name hyperlinks) his friends like Facebook with a unique ID associated with him, clicking each item, he will open a new chat page with a text box and a button and start chatting. Here is the code

start chat-with-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});
    });

      

+3


source to share


1 answer


hi root this might be useful for u



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 
        }
    );
});
});

      

+3


source







All Articles