Reputation: 144
Good evening SO-community, I tried really hard to fix this issue but I think I'll need your wisdom because I really don't know what's the matter here. I have a node.js server which is serving an index.html via express. I am currently starting to use socket.io.
This is the code on my client side:
$( document ).ready(function() {
document.getElementById("start").addEventListener("click", startGame);
function startGame() {
var socket = io(); console.log("Sending request to server");
socket.emit('connectToTable', {tableID: 1});
socket.on('successfulConnection', function(msg){
alert(msg);
}); }
});
This is the code on my server side:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require('express');
var port = process.env.PORT || 3000;
path = require('path');
app.use(express.static(path.join(__dirname, '/')));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("There is someone knocking on the door")
socket.on('connectToTable', function(socket){
console.log("Received player request")
var player = new Player(socket.id);
socket.emit('successfulConnection', "The connection to the server has been successful");
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
On my console on the server I see that "There is someone knocking on the door" gets printed hundreds or thousands of times per second which leads to a CPU load of 100%. At the same time I can see on the client-side (in Chrome) that hundreds of xhr polls are being made.
I really can't figure out why the connection is not established after the first connection attempt and retried sooo often. Furthermore I don't even really understand why it is even using xhr polling instead of websockets.
Help would be very highly appreciated. Thank you so much in advance.
Upvotes: 0
Views: 496
Reputation: 124
You have to use the same version of socket.io, on the client and on the server (I have had the same problem 5 days ago), check on console with:
npm list socket.io
the version of the server and look if you use the same version on the client, on index.html like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
You can get the url from here:
Regards
Upvotes: 3