skip to Main Content

I’ve been doing a lot of online courses with node and express. I want to get sockets.io to work but I can’t even establish a connection at the moment. I am using a cPanel virtual private server and running code in the server terminal and then trying to use a website hosted on the server to access the .js file running on the server.

I’ve tried all sorts of different things but I’m reducing it to its most basic level to try get a connection. All the videos I’ve seen are running on a local machine and using the command prompt on a local machine to run the .js file and the browser to access http://localhost:3000.

The .js file I’m running on my cPanel server looks like this;

var express = require('express');
var app = express();

app.get('/', function(req,res){
    res.send('Hello world 2');
})

app.listen(3000);

So how do I then access that via the browser? I have tried http://mywebsite.com:3000 and http://11.22.33.444:3000 if 11.22.33.444 is the server ip, but the browser just times out and there is no output in the server console.

ultimately I need to run a socket.io command that looks like this;

var socket = io.connect('http://localhost:3000');

and in all the tutorials I’ve seen they use this localhost:3000 but no one explains how to access this if its on an actual server so I’m pretty lost.

There are other examples like;

...
const http = require('http').createServer();
...
http.listen(3000 => () => {
  console.log('listening on port 3000');
});

That’s just a snippet of the code but I’m wondering how I then access that 3000 port from the browser without http://localhost:3000

3

Answers


  1. Chosen as BEST ANSWER

    Think I just solved it. I tried a different port and it worked :/


  2. IF you read the docs you will see that there is a guide how to connect it with express: https://socket.io/docs/

     var app = require('express')();
     var server = require('http').Server(app);
     var io = require('socket.io')(server);
    
     server.listen(3000);
     // WARNING: app.listen(3000) will NOT work here!
    
     app.get('/', function (req, res) {
       res.status(200).json({ message: "Connected" });
     });
    
     io.on('connection', function (socket) {
      console.log("somebody connected");
     });
    
    Login or Signup to reply.
  3. No need to specify any address in io.connect()

    const app = express();
    const http = require('http').Server(app);
    const io = require('socket.io')(http);
    
    
    
    http.listen(process.env.PORT || 3000, function() {
    });
    <script src="/socket.io/socket.io.js"></script>
    
          var socket = io.connect();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search