简体   繁体   English

Socket.IO和Node.js:不会将数据发送到服务器

[英]Socket.IO and Node.js: Won't send data to server

I am working on learning to use Socket.IO, and Node.JS, and I am trying to get started with making my own chat with it. 我正在努力学习如何使用Socket.IO和Node.JS,并且正在尝试开始自己的聊天。 however, the text is not showing up at all in the chat! 但是,聊天中根本没有显示文本! can someone help me out here? 有人可以帮我吗?

index.html 的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 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 的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"
  }
}

Is it because of the version of socket.io or express that is causing that, or what is it? 是由于socket.io或express的版本引起的,还是什么? if you know why, thank you! 如果您知道为什么,谢谢!

I just needed to move the script stuff to after the tag. 我只需要将脚本内容移到标记之后即可。 nvm then! 那么nvm!

有时我遇到相同的问题,当我使用broadcast.emit时收到msges

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

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

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