【问题标题】:Socket.IO and Node.js: Won't send data to serverSocket.IO 和 Node.js:不会向服务器发送数据
【发布时间】:2017-02-05 04:46:14
【问题描述】:

我正在努力学习使用 Socket.IO 和 Node.JS,并且我正在尝试开始与它进行自己的聊天。但是,聊天中根本没有显示文字!有人可以帮我吗?

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>
  <script src="/socket.io/socket.io.js"></script>
  <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
  <script>
   var socket = io();
   $('form').submit(function(){
     socket.emit('chat message', $('#m').val());
     $('#m').val('');
     return false;
   });
   socket.on('chat message', function(msg){
     $('#messages').append($('<li>').text(msg));
   });
 </script>
 <body>
    <ul id="messages"></ul>
    <form action="">
       <input id="m" autocomplete="off" /><button>Send</button>
    </form>
 </body>
</html>

index.js

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

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

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

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

package.json

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

是因为 socket.io 或 express 的版本导致的,还是什么原因?如果你知道为什么,谢谢!

【问题讨论】:

  • 你有没有在你的js和节点服务器中添加一些console.log调用来查看聊天消息是否正在发送和接收?您可以在浏览器中查看/socket.io/socket.io.js 吗?

标签: javascript node.js socket.io


【解决方案1】:

我只需要将脚本内容移到标签之后。那么nvm!

【讨论】:

    【解决方案2】:

    我以前也遇到过同样的问题,当我使用广播时它收到了消息。发射

     io.broadcast.emit('chat message', msg);
    

    【讨论】:

      猜你喜欢
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 2012-12-31
      • 2021-03-20
      • 1970-01-01
      • 2013-05-10
      相关资源
      最近更新 更多