Node.js & Socket.io 添加用户名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18649705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:31:59  来源:igfitidea点击:

Node.js & Socket.io Adding Username

javascriptnode.jssocketssocket.io

提问by Joenel de Asis

I'm new to socket.io I would like to know how do i add username in this simple chat using socket.io. Thanks in advance guys. I would like to learn socket programming.

我是 socket.io 的新手,我想知道如何使用 socket.io 在这个简单的聊天中添加用户名。在此先感谢各位。我想学习套接字编程。

The code below is my server.js

下面的代码是我的 server.js

//chat service
io.sockets.on('connection', function (socket) {
    socket.on('sendMessage', function (data) {
    socket.broadcast.emit('message', data);
    socket.emit('message', { text: data.text });   
    });   
});

This is my chat client index.html

这是我的聊天客户端 index.html

<!-- index.html -->
<html> 
  <body>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        var socket = io.connect('http://localhost');
        socket.on('message', function (data) {

          $('#chat').append( '<b>' + data.text + '</b>' + '<br />');

        });
            $('#send').click(function () {
            socket.emit('sendMessage', { text: $('#text').val() });
            $('#text').val('');
        });

            $('#text').keypress(function(event) {
              if(event.keyCode == 13) {
                $('#send').click();
                $('#text').val('');
              }
            });

      });
    </script>

    <div id="chat" style="width: 500px; height: 300px; border: 1px solid black">

    </div>    

    <input type="text" name="text" id="text">
    <input type="button" name="send" id="send" value="send">
  </body>
</html>

回答by Tamas

Have a look here - http://www.tamas.io/2013/05/19/simple-chat-application-using-node-js-and-socket-io/

看看这里 - http://www.tamas.io/2013/05/19/simple-chat-application-using-node-js-and-socket-io/

The easiest way is to add a people's object - see the source code (link in the article).

最简单的方法是添加一个人的对象 - 请参阅源代码(文章中的链接)。

If you want to implement rooms as well, read this: http://www.tamas.io/2013/05/19/simple-chat-application-using-node-js-and-socket-io/

如果你也想实现房间,请阅读:http: //www.tamas.io/2013/05/19/simple-chat-application-using-node-js-and-socket-io/

Have fun.

玩得开心。