簡體   English   中英

Socket.io不會發出事件

[英]Socket.io wont emit events

我開始學習socket.io。 我以socket.io網站示例開始本教程,我正確安裝了所有東西,但是我認為socket無法在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.on('chat message') console.log consloe.log錯誤為consloe.log 這就是為什么它崩潰了並且沒有發出信號的原因。

另外,在服務器和瀏覽器上使用最新版本的socket.io。

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

請檢查此作為參考--- https://socket.io/docs/emit-cheatsheet/#

io.to(room).emit('msg'msg)或ease socket.emit('hello','您能聽到我說話嗎?',1,2,'abc');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM