Socket.io Emit不起作用

时间:2018-07-26 13:27:40

标签: javascript html node.js socket.io

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

这是我的代码:

App.js

li

Index.html

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);
});

4 个答案:

答案 0 :(得分:3)

您聆听单个./prod/js/main.js, ./prod/js/main2.js // so on 。将您的听众从socket移到io

client

答案 1 :(得分:1)

您应该像这样在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);
    });
});

答案 2 :(得分:0)

该事件在服务器上的套接字(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);
});

答案 3 :(得分:0)

尝试这样做。

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

    client.on('sendmsg', function(data) {
        console.log(data);
    });
});
相关问题