socket.io聊天无法正常工作

时间:2015-11-10 18:33:18

标签: javascript socket.io

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

HTML:

SDLManager::SDLManager() {

    // ......

    // THIS BREAKS
    Constants::window = SDL_CreateWindow("Caption", 
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 
        Constants::w, Constants::h, SDL_WINDOW_SHOWN);
}

Index.js:

<!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>

控制台日志:

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');
});

帮助我需要像这样的索引以使其工作无法改变它。 不确定为什么它不起作用我认为该消息没有发送。

由于

1 个答案:

答案 0 :(得分:0)

您似乎在复制 Socket.io 聊天示例时犯了一些错误。首先,您无法在submit上制作<div>。只能提交<form>个。其次,将<div>的邮件移出<form>,因为它们与您下一条邮件提交的信息无关:

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