Asad ullah
Asad ullah

Reputation: 716

how to connect to socket.io on live server using nodejs

Its almost a week I'm having trouble with putting my node.js application online. I have a shared hosting where I created an subdomain (let's say sub.domain.com) and this subdomain is pointed to an directoy /home/wproj/myapp which contains code of my nodejs application. I logged into server using SSH and executed following commands exactly.

cd myapp
node index.js

Now node application is started on port 3000 but I cannot access its webpage from browser. so I used an .htaccess file which contains following code.

RewriteEngine On
RewriteRule ^$ http://127.0.0.1:3000/ [P,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://127.0.0.1:3000/$1 [P,L]

Now i can see the webpage at http://sub.domain.com/. But problem is my server is emitting an socket but client is not able to connect to that socket. On local server it was working perfectly fine, I don't seem to find any solution from hundreds of already asked questions I visited. In browser console, it says that

Firefox can’t establish a connection to the server at ws://sub.domain.com/socket.io/?EIO=3&transport=websocket&sid=pItfylCcSBwvBrGaAAAZ.

My client side code looks like this.

const socket = io.connect("http://sub.domain.com/");

I also tried entering port number like this

const socket = io.connect("http://sub.domain.com:3000/");

it didn't worked either. Also tried to replace 127.0.0.1:3000 with http://sub.domain.com:3000 and still socket is not connecting and always returns 404

I'm sorry for the long question, but I had to tell the whole story. If anyone can help me or point me in the right direction, I'll be grateful.

Thanks.

Upvotes: 2

Views: 1889

Answers (1)

bnitica
bnitica

Reputation: 11

You need to have the port 3000 open for inbound and outbound traffic. Since it is a shared hosting you need to check if you can do this by yourself from the admin panel (cPanel for example) before writing a ticket to the support.

You can run this command grep -w 3000/tcp /etc/services to see if the port appears in the running services list.

You can investigate the network panel from Web Development Tools (Ctrl + Shift + I in your browser). If you see the No 'Access-Control-Allow-Origin' header is present on the requested resource. error then you need to start your server like this: io = require('socket.io')(httpServer, {'origins': 'sub.domain.com:*'})

Upvotes: 1

Related Questions