Categories
express javascript node.js socket.io

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="https://www.faqcode4u.com/faq/570547/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?