Matthew
Matthew

Reputation: 453

How to make remote websocket connection to nodejs server on heroku

I'm trying to connect to a nodejs server over a websocket connection but can't get anything to work.

My server.js looks like this:

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io', {
    transports: ['websocket']
})(http);

var server_port = process.env.PORT || 8080
var server_ip_address = process.env.IP || '0.0.0.0'

app.listen(server_port, server_ip_address, function () {
    console.log('listening on ' + server_ip_address + ":" + server_port);
});

My client.js (running on a raspberry pi also running nodejs) is:

var io = require('socket.io-client');
var socket = io.connect('http://<app-url>',
    {
        reconnect: true,
        transports: ['websocket']
    }
);

socket.on('connect', function(socket) {
    console.log('Connected!');
});

I've also tried on openshift v2 (ports 8000 and 8443) and v3 and no luck there.

If anyone has done this recently please let me know how, thanks!

When debugging the client I get the message:

engine.io-client:socket socket close with reason: "transport error"

and on the server:

heroku[router]: at=error code=H13 desc="Connection closed without response"

Upvotes: 1

Views: 2397

Answers (2)

Matthew
Matthew

Reputation: 453

Ok, it's working now. I modified the example in the heroku docs

I'm not quite sure why my server config doesn't work, but the following does work:

server.js

var express = require('express');
var socketIO = require('socket.io');
var path = require('path');

var PORT = process.env.PORT || 3000;

var app = express();
var server =  app.listen(PORT, () => console.log(`Listening on ${ PORT }`));

var io = socketIO(server);

io.on('connection', (socket) => {
    console.log('Client connected');
    socket.on('disconnect', () => console.log('Client disconnected'));
});

client.js (xShirase was right in saying I needed the correct path here...)

var io = require('socket.io-client');
var socket = io.connect('https://<url>',
    {reconnect: true, transports : ['websocket'], path: '/socket.io'});

socket.on('connect', function (socket) {
    console.log('Connected!');
});

Upvotes: 1

xShirase
xShirase

Reputation: 12399

It looks like a strange bug that happens sometimes, you should be able to get through by adding the path of your client library in the options like so :

var socket = io.connect('http://<app-url>:8080',
    {
        reconnect: true,
        transports: ['websocket'],
        path: "/lib/socket.io.js"  //use the relevant path for your file
    }
);

But you seem to be using the default options anyway, so you could just do :

var socket = io.connect();

Upvotes: 1

Related Questions