【问题标题】:How to build a Node.js WebSocket Chat App with Socket.io?如何使用 Socket.io 构建 Node.js WebSocket 聊天应用程序?
【发布时间】:2019-11-07 03:10:47
【问题描述】:

我正在尝试使用 socket.io 构建一个聊天应用程序。我的所有代码都与文档相同。但是我的代码不起作用,我找不到问题所在。我在哪里做错了?

index.html:

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function () {
        var socket = io();
        $('form').submit(function(e){
          e.preventDefault(); // prevents page reloading
          socket.emit('chat message', $('#m').val());
          $('#m').val('');
          return false;
        });
        socket.on('chat message', function(msg){
          $('#messages').append($'<li>').text(msg);
        });
      });
    </script>
  </body>
</html>

index.js:

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);


http.listen(3000, function(){
  console.log('listening on *:3000');
});

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
    console.log('a user connected');

    socket.on('disconnect', function(){
        console.log('user disconnected');
    });

    socket.on('chat message', function(msg){
        console.log('message: '+ msg);

        socket.on('chat message', function(msg){
            io.emit('chat message', msg);
        });
    });
});

package.json:

{
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {
    "express": "^4.17.1",
    "socket.io": "^2.2.0"
  }
}

根据这些代码,当我向服务器发送消息时,希望在其他客户端看到我的消息,但甚至不会出现在发件人中。

【问题讨论】:

    标签: html node.js websocket socket.io chat


    【解决方案1】:

    感谢您的帮助。我发现了问题,这是$('#messages').append($'&lt;li&gt;').text(msg);这一行的html文件中的js代码语法错误。应该是$('#messages').append($('&lt;li&gt;').text(msg));

    【讨论】:

      【解决方案2】:

      删除您嵌套在第一个socket.on("chat message") 中的第二个socket.on("chat message")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-10
        • 1970-01-01
        • 1970-01-01
        • 2016-09-08
        • 2012-08-11
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        相关资源
        最近更新 更多