karthick kannan
karthick kannan

Reputation: 21

chat with particular user in node.js

This is my code for private chat with selected user. It is not sending message to the selected user like private message.

server side:

   var fs = require('fs'),
    http = require('http'),

    sio = require('socket.io');




  var server = http.createServer( function(req, res) {

    if (req.url === '/index') {
        fs.readFile('./index.html', function(err, page) {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write(page);
            res.end();

        });
    }
    else if (req.url === '/karthick') {
        fs.readFile('./karthick.html', function(err, page) {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write(page);
            res.end();
        });
    }
    else if (req.url === '/raj') {
        fs.readFile('./raj.html', function(err, page) {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write(page);
            res.end();
        });
    }

else if (req.url === '/Harendra') {
        fs.readFile('./Harendra.html', function(err, page) {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write(page);
            res.end();
        });
    }
    else if (req.url === '/send') {
        fs.readFile('./sendingmsg.html', function(err, page) {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write(page);
            res.end();
        });
    }
    else {
            res.writeHead(301,
              {Location: '/index'}
            );
            res.end();
        }
});
server.listen(8000, function() {
  console.log('Server listening at http://192.168.1.16/8000');
});
io = sio.listen(server);
// store messages
var messages = [];

io.sockets.on('connection', function(socket){
  socket.on('chat message', function(msg){
    console.log('Received: ', msg);
    messages.push(msg);
    io.sockets.emit('chat message', msg);
  });
  messages.forEach(function(msg) {
    socket.send(msg);
  })
});

client side:sending

<!DOCTYPE html>
<html>
    <body>
        <title>send message</title>
        <ul id="messages"></ul>
        <form action="">
            <select>
                 <option id="kar"  value="karthick">karthick</option>
                 <option id="raj" value="Raj">Raj</option>
                 <option id="haren" value="Harendra">Harendra</option>
          </select><br />
             <textarea id="m"  rows="4" cols="50">

            </textarea><br/>
                <button id=btn>Send</button>
        </form>
         <script src="https://cdn.socket.io/socket.io-1.1.0.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      var socket = io.connect('http://192.168.1.21:8000');
      $('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
      });
      socket.on('disconnect', function() {
        $('#messages').append('<li>Disconnected</li>');
      });
     </script>
    </body>
</html>

received client:1

<!DOCTYPE html>
<html>
    <body>
        <title>Users</title>
        Welcome Harendra
        <ul id="messages"></ul>
        <script src="/socket.io/socket.io.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
        <script>
         $(function(){
    var socket = io.connect();
    socket.on('connect', function () {
      socket.on('message', function(message) {
        $('#messages').append($('<li>').text(message));
      });
      socket.on('disconnect', function() {
        $('#messages').append('<li>Disconnected</li>');
      });
    });


  });
        </script>

    </body>
</html>

When I select user for sending private message it is not working. Please help me someone

Upvotes: 1

Views: 147

Answers (1)

Vitalii Zurian
Vitalii Zurian

Reputation: 17976

You are missing some logic in your server sockets implementation.

Instead of sending the message to ALL clients with io.sockets.emit(...) you should send it to a particular room - socket.to(...).emit(...)

Please, have a look at the documentation

Here is the abstract logic:

  1. You socket should belong to a certain room in order to receive "private" messages (socket.join(...))

    socket.join('roomName');
    
  2. You should broadcast your "private" messages to a specific room instead of broadcasting them to all clients. You can do it be specifying the room (socket.to(...)):

    socket.to('roomName').emit('chat message', msg);
    

Upvotes: 1

Related Questions