繁体   English   中英

socket.io 聊天不起作用

[英]socket.io chat not working

嘿,这是我的 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>

索引.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

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

谢谢

您在复制Socket.io聊天示例时似乎犯了一些错误。 首先,你不能在<div>submit 只有<form>可以提交。 其次,将带有消息的<div>移出<form> ,因为它们与随下一条消息一起提交的信息无关:

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

暂无
暂无

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

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