簡體   English   中英

Socket.io事件未觸發

[英]Socket.io event not firing

這是完整的代碼:-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的新手。 謝謝

您正在從服務器發送錯誤消息。

在服務器上,更改此:

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

對此:

socket.emit('chatOUT', msg);

您的客戶代碼正在偵聽chatOUT消息,因此這是需要發送的確切消息名稱。 這是匹配的客戶端代碼:

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

暫無
暫無

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

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