【问题标题】:socket.io chat not workingsocket.io 聊天不起作用
【发布时间】:2015-11-11 23:43:54
【问题描述】:

嘿,这是我的 socket.io 聊天,来自网站示例... 为什么这不起作用?

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>
        <div class="chatOverlay">
         <div class="chatMessages"></div>
         <input type="text" id="sendMessage" placeholder="Enter Chat Message..." maxlength="80">
      </div>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      var socket = io();
      $('.chatOverlay').submit(function(){
        socket.emit('chat message', $('#sendMessage').val());
        $('#sendMessage').val('');
        return false;

      });
      socket.on('chat message', function(msg){
        $('.chatMessages').append($('<li>').text(msg));
        console.log (msg);
              });
    </script>
  </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){
    console.log('a user connected');
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
    console.log('message: ' + msg);

  });
});

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

控制台日志:

listening on *:3000
a user connected
a user connected

感谢您的帮助,我需要这样的索引才能使其正常工作,无法更改它。 不知道为什么它不起作用,我认为消息没有发送。

谢谢

【问题讨论】:

  • 服务器端和客户端是否都有错误?
  • 如果您不知道消息是否已发送,请开始查看开发者控制台。 “不工作”也是对问题的不充分描述。
  • 不,我没有得到任何错误,是的,我很抱歉,但不能做更多......

标签: javascript socket.io


【解决方案1】:

您似乎在复制 Socket.io 聊天示例时犯了一些错误。首先,您不能在&lt;div&gt; 上创建submit。只能提交&lt;form&gt;s。其次,将带有消息的&lt;div&gt;移出&lt;form&gt;,因为它们与您的下一条消息中提交的信息无关:

<body>
  <div class="chatMessages" />
  <form class="chatOverlay">
    <input type="text" id="sendMessage" placeholder="Enter Chat Message..." maxlength="80">
  </form>
...

【讨论】:

    猜你喜欢
    • 2017-06-20
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2016-12-20
    • 2014-02-10
    • 2020-10-02
    • 1970-01-01
    相关资源
    最近更新 更多