Socket.io works with localhost but not on Heroku server
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 **herokuthe url must delete " : port"
ws://<heroku app name>.herokuapp.com/socket.io/?EIO=4&transport=websocket
It's work for me!
I have deployed your code with minor changes and its working fine on heroku please take a look into it.Server side app.js
var express = require('express');var app = express();app.set('port', (process.env.PORT || 5000));var server = app.listen(app.get('port'), function() { console.log('Node app is running on port', app.get('port'));});var io = require('socket.io')(server);app.use(express.static("./views"));app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next();});app.get('/', function (req, res) { var path = __dirname + '/views/index.html'; console.log(path); res.sendFile(path);});io.on('connection', function(socket) { socket.on('beep', function(){ socket.emit("beep", {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); });});
package.json
{ "name": "socketio", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start" : "node app.js" }, "author": "inampaki", "license": "ISC", "dependencies": { "express": "^4.13.3", "express-ws": "^0.2.6", "socket.io": "^1.3.7" }}
index.html
<script src="/socket.io.js"></script><script> var socket = io.connect('/'); socket.on('speed', function (data) { console.log('speed Message Received!'); console.log(data); }); socket.on('beep', function (data) { console.log('beep Message Received!'); console.log(data); }); socket.emit("beep", {beep : true}); socket.emit("change-speed", {"change-speed" : true}); socket.emit("ios-connection", {"ios-connection" : true});</script>
note that save index.html and socket.io.js in views folder. URL on which I have deployed it is socketip