Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io keeps connecting repeatedly and ignores other events

I'm attempting to make a webapp where users can play toroidal chess with each other. This is my app.js, on the server:

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 8000;

app.use(express.static('public'));
app.get('/', function(req, res) {
  res.sendFile(__dirname + '/public/index.html');
  console.log("Got request for homepage");
});

io.on('connection', function(socket){
   console.log('A client has connected to the server');
   socket.on('move', function(moveString){
     console.log("Move made: " + moveString);
   });
  socket.on('disconnect', function(){
    console.log('A client has disconnected from the server');
  });
});

http.listen(port, function() {
    console.log('listening on *: ' + port);
});

The public directory contains files like index.html which contains the chessboard, as well as some javascript and CSS files that control the board and only allow legal moves. board.js is the main file for this.

On the client-side, my index.html file contains the line:

<script src="js/board.js"></script>

My board.js file contains the line:

var socket = io();

and also in the move validating function, whenever a valid move is made, I have the line

socket.emit('move', moveString);

However, whenever I run node app.js from the terminal and then visit localhost:8000 in a web browser, the terminal repeatedly displays that "A client has connected to the server", multiple times per second, like this:

Screenshot of terminal

Also, whenever I make a move or move to another page from the browser, the server doesn't seem to register those events (it doesn't log "A client has disconnected from the server", nor does it log that a move has been made). What am I doing wrong?

like image 667
Zanik Avatar asked Jan 03 '18 00:01

Zanik


1 Answers

OK, it appears you're running socket.io v2.0.4 on the server and v1.2.0 on the client. Having mismatched version numbers like that can cause the behavior you see which is actually a failure to connect properly which causes an immediate attempt to reconnect and it just never stops doing that.

You can get the correct version directly from the server by using this in the client:

<script src="/socket.io/socket.io.js"></script>

The socket.io server has a pre-built route handler for /socket.io/socket.io.js and it will automatically serve the right matching client version from within the node_modules directory when that request comes in.

If you want the client to come from a CDN, then you need to get the CDN version that exactly matches the server version and anytime you upgrade the server version, you have to fix the CDN version to match.

like image 102
jfriend00 Avatar answered Oct 19 '22 08:10

jfriend00