简体   繁体   English

与node.js中的特定用户聊天

[英]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 接待客户: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 请帮我一个人

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(...) 而不是使用io.sockets.emit(...)将消息发送给所有客户端,您应该将其发送到特定的房间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(...)

     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(...) ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM