0
votes

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">
4
Maybe the example here can help: gist.github.com/jeffdonthemic/87b542cc09864fe203f4 - Juky

4 Answers

4
votes

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

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

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

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