CiscoKidx
CiscoKidx

Reputation: 920

socket.emit from node.js client to browser client

I am trying to emit a message from the node.js client to the web client. I am assuming this must be done through the server. Any help is appreciated.

The erorr I see in the browser is:

GET http://10.1.0.47/socket.io/?EIO=3&transport=polling&t=1438260260496-8 net::ERR_CONNECTION_REFUSED

node.js Client:

socket.emit('clientMessage', jsonData, 'Pi-Voyager');

Server:

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

var port = process.env.PORT || 8080;

server.listen(port, function() {
    console.log('Gulp is starting my app on PORT: ' + port)
});

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

io.on("connection", function(socket) {

    socket.on('clientMessage', function(jsonData, from) {
        socket.emit('serverMessage', 'Got a message!', jsonData);
        console.log('Data being sent from', from, 'is:\n' + jsonData);
    });

});

web client:

<body>
    <h1>9.html</h1>
    <div id="messages"></div>
    <script src="/socket.io/socket.io.js"></script>
    <script>

        var socket = io.connect("/");

        socket.on("serverMessage", function(msg) {
            document.getElementById("messages").innerHTML += msg + "<br>";
        })

    </script>   
</body>

Upvotes: 0

Views: 562

Answers (1)

ralh
ralh

Reputation: 2564

You are probably having the server listen on port 8080. And I don't think your client connects there. Try changing

var port = process.env.PORT || 8080;

to

var port = process.env.PORT || 80;

Also, even if you actually connect, you need to get two different sockets - from your web app and node client app. Because currently, you are taking input from a socket and writing it into the same socket - basically an echo server.

From the io.on('connect') callback you get a socket - that is a connection with a SINGLE client. If you write to it, you write to that client, if you receive from it, you receive from that client. To make an app broadcasting to all clients (like a chat) you can do this.

var sockets = [];
io.on('connection', function(socket) {
   sockets.push(socket);
   socket.on('clientMessage', function(jsonData) {
       for(var i = 0, len = sockets.length; i < len; ++i) {
           sockets[i].emit('serverMessage', 'Got a message!', jsonData);
       }
   });
});

Upvotes: 2

Related Questions