简体   繁体   中英

Socket.io Emit doesn't work

I'm a newbie in NodeJS and I just started creating a simple chat app with Express and Socket.io but It the "message" emit part is not working (socket.on('connect') works!). The alert "OK" works fine but console.log doest nothing.

Here is my code:

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

Index.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"> 

You listen on individual socket . Move your listener from io to 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);
    });
});

You should move your handler inside the on connection function like this:

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

The event gets triggered on the socket ( client ) not on the server:

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

Try doing this way.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM