We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello all.
I have the following example using Node.js for the server that sends data via Socket.io to a Javascript file (P5.js). All works well locally, but when I uploaded to Heroku, it does not. I have tried a lot of tips I found online, but I am always stuck and can't get it through. At the moment, I don't get errors, but I also can't see the values coming.
Here is the code I use at the moment:
var express = require('express');
var socket = require('socket.io');
//store the express functions to var app
var app = express();
//Create a server on localhost:3000
var server = app.listen(process.env.PORT || 3000);
//var server = app.listen((process.env.PORT || 3000, function(){
//console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
//});
//host content as static on public
app.use(express.static('public'));
console.log("Node is running on port 3000...");
//assign the server to the socket
var io = socket(server);
//dealing with server events / connection
io.sockets.on('connection', newConnection); //callback
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
//The maximum is exclusive and the minimum is inclusive
return Math.floor(Math.random() * (max - min)) + min;
}
//function that serves the new connection
function newConnection(socket){
console.log('New connection: ' + socket.id);
socket.on('incomingDataToServer', emitFunction);
function emitFunction(data){
//setInterval(() => socket.broadcast.emit('ServerToClient', new Date().toTimeString()), 1000);
let randNum;
setInterval(function(){
//get a random value, and assign it a new variable
randNum = getRandomInt(0, 100);
}, 1000);
socket.broadcast.emit('ServerToClient', randNum);
//following line refers to sending data to all
//io.sockets.emit('mouse', data);
console.log(randNum);
}
}
And the Javascript here:
let socket;
function setup(){
socket = io();
socket.on('ServerToClient', socketEvents);
}
function socketEvents(data){
incomingData = data;
console.log(data);
}
Any help is appreciated.
Thanks
Answers
At socket.io it says "Notice that I’m not specifying any URL when I call io(), since it defaults to trying to connect to the host that serves the page."
Are you serving the html with the JavaScript code from the same server that runs the node.js server? Maybe you should specify the IP or URL in the client? See https://socket.io/docs/client-api/