Skyler Spaeth
Skyler Spaeth

Reputation: 193

socket.io - socket.send doesn't communicate message

I am trying to communicate text between front and back end. My node.js code looks like this:

var express = require('express');
var app = express();
var io = require('socket.io').listen(8081);

app.use(express.static('public'));

var server = app.listen(3000, function () {
  var port = server.address().port;
  console.log('Example app listening at', port);

  io.sockets.on('message', function (message) {
    console.log(message);
  });

});

The markup:

<html>
<body>
    <script type="text/javascript" src="https://cdn.socket.io/socket.io-1.3.7.js"></script>
    <script type="text/javascript">
          var socket = io.connect('http://localhost:8081');
          socket.on('connection', function (socket) {
            socket.send('hi');
          });
    </script>
</body>
</html>

I am pretty new to socket.io, and socket.send('hi') should be console.loging hi to the node console. Is there something I am missing (yes, the IP is right)? There are no JS console errors.

Upvotes: 1

Views: 134

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191799

I don't think you can use io.sockets.on -- you can only use it to .emit to connected sockets.

Additionally, for the frontend the event when the socket connects is connect. connection is the server side event for when a new connection is created.

Finally, the socket is not passed as an argument to the event on the frontend either.

// server
io.on('connection', socket => socket.on('message', msg => console.log(msg)));

// client
socket.on('connect', () => socket.send('hi'));

Upvotes: 2

Related Questions