【问题标题】:Socket.io event not firingSocket.io 事件未触发
【发布时间】:2017-03-12 02:25:07
【问题描述】:

这是完整的代码:- 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>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {
    var socket = io();
    $('form').submit(function(){
      socket.emit('chatIN', $('#m').val());
      $('#m').val('');
      return false;
    });
socket.on('chatOUT', function(msg){
  $('#messages').append('<li><span>'+msg+'</span></li>');
    });
  });
</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.sockets.on('connection', function(socket){
    socket.on('chatIN', function(msg){
        console.log('message:'+ msg);
        socket.emit('chatOUT:'+ msg);
    });
    socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

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

我在尝试 socket.io 初学者教程时遇到问题,我按照本教程进行操作 https://socket.io/get-started/chat/

一切似乎都还好,直到最后一件事,当他们构建一个聊天应用程序时,当你在文本框中点击提交时,它会更新元素的内容。

我可以看到消息在 node js 控制台中打印,但在 chrome 的控制台中没有。我还尝试使用开发人员选项对其进行调试,但控件永远不会进入 index.html 中的此方法。

socket.on('chat message', function(msg){

有人可以帮忙吗?我对 socket.io 和 nodejs 真的很陌生。 谢谢

【问题讨论】:

  • 请提供更多代码。这里没有太多信息可以帮助您...
  • @MithunS - 在这个网站上,您的代码必须粘贴到您的问题中,而不仅仅是通过外部链接引用。这是因为外部链接有随时间变化或消失的令人讨厌的习惯,从而破坏了问题作为未来人参考的价值。因此,请将代码的相关部分直接粘贴到您的问题中并适当格式化。

标签: node.js socket.io


【解决方案1】:

您从服务器发送了错误的消息。

在服务器上,改变这个:

socket.emit('chatOUT:'+ msg);

到这里:

socket.emit('chatOUT', msg);

您的客户端代码正在侦听chatOUT 消息,因此这是需要发送的确切消息名称。这是匹配的客户端代码:

socket.on('chatOUT', function(msg){...}

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    相关资源
    最近更新 更多