【问题标题】:Socket.io wont emit eventsSocket.io 不会发出事件
【发布时间】:2017-07-05 09:06:17
【问题描述】:

我开始学习 socket.io。 我从 socket.io 网站示例开始本教程 我正确安装了所有东西,但我认为套接字无法在 index.html 中发出事件 任何人都可以提供帮助

这是我的代码 index.js

    var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(Socket){
    Socket.on('chat message', function(msg){
    consloe.log('hi');
    io.emit('chat message', msg);
  });
});

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

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; }
      #messages { margin-bottom: 40px }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {
    var socket = io();  
    $('form').submit(function(){
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      console.log('sample');
      return false;
    });
    socket.on('chat message', function(msg){
        console.log('sample');
      $('#messages').append($('<li>').text(msg));
    });
  });
</script>
  </body>
</html>

【问题讨论】:

  • 在客户端使用socket.io-client
  • 我用过,你可以在代码中看到
  • 您正在从 cdn 提供 socket.io。客户端的 socket.io 版本应该与服务器上使用的版本匹配。
  • 当前版本是 2.0.3 但您在客户端使用的是 1.2.0

标签: javascript node.js sockets socket.io


【解决方案1】:

您在服务器上的Socket.on('chat message') 中将console.log 输入错误为consloe.log。这就是它崩溃而不发射的原因。

另外,在服务器和浏览器上使用最新版本的 socket.io。

https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js

【讨论】:

    【解决方案2】:

    请将此作为参考 --- https://socket.io/docs/emit-cheatsheet/#

    io.to(room).emit('msg'msg),或者elase socket.emit('hello', '你能听到我吗?', 1, 2, 'abc');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 2019-10-30
      • 2019-05-01
      • 2012-04-19
      • 1970-01-01
      相关资源
      最近更新 更多