【问题标题】:Socket.io Emit doesn't workSocket.io Emit 不起作用
【发布时间】:2019-01-03 12:30:07
【问题描述】:

我是 NodeJS 的新手,我刚开始使用 Express 和 Socket.io 创建一个简单的聊天应用程序,但是“消息”发出部分不起作用(socket.on('connect') 有效!)。警报“OK”工作正常,但 console.log 什么也没做。

这是我的代码:

App.js

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);


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

app.get('/test', function(req, res,next) {
    res.render('HALLO ');
});

server.listen(4200);

io.on('connection', function(client) {
   // var address = io.handshake.address;
    console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ')
});



io.on('sendmsg', function(data) {
    console.log(data);
});

索引.html

<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

<script>
    var socket = io.connect('http://localhost:4200');

    function sendMsg(){
        alert("OK");
        socket.emit('sendmsg', document.getElementById("text").value);
    }
</script>
<h2>Awesome Chat by Simon</h2>
<br>
    <input type="text" id="text">
    <input type="button" onclick="sendMsg()" value="Senden">

【问题讨论】:

标签: javascript html node.js socket.io


【解决方案1】:

您收听个人socket。将您的听众从io 移动到client

io.on('connection', function(client) {
   // var address = io.handshake.address;
    console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ')

    client.on('sendmsg', function(data) {
        console.log(data);
    });
});

【讨论】:

    【解决方案2】:

    你应该像这样在connection 函数中移动你的处理程序:

    io.on('connection', function(client) {
       // var address = io.handshake.address;
        console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ');
        client.on('sendmsg', function(data) { // Move this part inside the connection function
          console.log(data);
        });
    });
    

    【讨论】:

      【解决方案3】:

      事件在套接字 (client) 上触发,而不是在服务器上:

      io.on('connection', function(client) {
         // var address = io.handshake.address;
         console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ');
         client.on("sendmsg", console.log);
      });
      

      【讨论】:

        【解决方案4】:

        尝试这样做。

        io.on('connection', function(client) {
            console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ')
        
            client.on('sendmsg', function(data) {
                console.log(data);
            });
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多