I am currently trying to use socket.io and a node.js server to communicate with a Unity script. I have everything hooked up and working with localhost, but for some reason when I port it to my Heroku server it can't connect. I'm assuming it might have something to do with the URL's? I'm new to socket.io so any help would be appreciated.
My node.js server:
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
var path = require('path');
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('beep', function(){
socket.emit("speed", {data: 5});
console.log('beep recieved');
});
socket.on('change-speed', function(data) {
console.log('change speed recieved: ' + data);
socket.emit("speed", {newSpeed: data});
});
socket.on('ios-connection', function(data) {
console.log('ios connection with message: ' + data);
});
});
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
My connection URL:
ws://<heroku app name>.herokuapp.com:5000/socket.io/?EIO=4&transport=websocket
The problem is almost certainly an incorrect port number.
In your application, you are checking for process.env.PORT
and if it is not set, you are defaulting to 5000.
In your ws URL however, you seem to be always expecting your application to be listening on port 5000.
You can check the config settings of your application by running the following command in the root of your project:
heroku run printenv
This will print a list of config vars, including the current set PORT
value, eg:
PORT=9352
You should use this port when constructing your ws URLs, eg:
ws://your-app.herokuapp.com:9352/socket.io/?EIO=4&transport=websocket
I found the way!!. In Unity
if you run server in the localhost. the url should have " : port" example (port = 5000)
ws://127.0.0.1:5000/socket.io/?EIO=4&transport=websocket
but if you have deployed to **heroku the url must delete " : port"
ws://<heroku app name>.herokuapp.com/socket.io/?EIO=4&transport=websocket
It's work for me!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With