Client unable to connect to server with socket.io - javascript

I'm having trouble with being able to connect to my node.js server from an external domain. It works fine when running it locally using the http web server through node however when connecting externally, it loads the socket.io.js file just fine but when trying to use the socket it removes the port from the URL and cannot connect.
Instead of doing this in the network requests:
http://external-domain.com:3000/socket.io/?EIO=3&transport=polling&t=M06GOUU
it does this:
http://external-domain.com/socket.io/?EIO=3&transport=polling&t=M06GOUU
I'm not sure how to make it not remove the port from the connection. How do I go about fixing this?
SERVER
const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const publicPath = path.join(__dirname, '../public');
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
app.use(express.static(publicPath));
server.listen(3000, () => {
console.log(`Server is up on port 3000`);
});
CLIENT SCRIPT TAG
<script src="http://external-domain.com:3000/socket.io/socket.io.js"></script>
CLIENT JS ON A DIFFERENT DOMAIN
var socket = io();
socket.connect('http://external-domain.com:3000');
socket.on('connect', function () {
console.log('Connected to server.');
});

Change from this:
var socket = io();
socket.connect('http://external-domain.com:3000');
to just this:
var socket = io("http://external-domain.com:3000");
And, you don't use the socket.connect() as you will already have requested the connection with the io("http://external-domain.com:3000"); call.
Explanation
The code:
var socket = io();
uses the page URL to connect to a socket.io server at that origin. That is not what you want (apparently).
If you wanted to use the .connect() method, it would be like this:
var socket = io.connect("http://external-domain.com:3000");
Note: var socket = io(url) is simply a shortcut for var socket = io.connect(url).
socket.connect() does not accept a URL as a parameter so you simply weren't using that correctly. It's just a synonym for socket.open().

Use io.connect("url")
var socket = io.connect("http://external-domain.com:3000", { rejectUnauthorized: false });
// { rejectUnauthorized: false } is an optional parameter.
Hope this works for you.

Related

Socket io timeout connecting to heroku socket io server with custom namespace

I'm trying to connect to my server located in heroku with socket io with this code, which works when the server is ran locally but, when I try to connect to the same server on herkoku it won't connect and it will give me a timeout.
I've tried setting transport to websocket on the client and it gives me websocket error on chrome and can't establish connection on firefox.
Client side code:
const io = require('socket.io-client');
socket = io.connect('https://herokuappurl.com:23840/custom_nsp');//not works
socket = io.connect('localhost:23840/custom_nsp');//works
Server side code:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const PORT = process.env.PORT || 8000;
var server = http.listen(PORT,function(){
print('listening on *:' + PORT);
});
io.of('/custom_nsp').on('connection', function(socket) {
/*socket.on events*/
}
I downgraded to version 1.7 at it works now.

What do I replace "http://localhost:3000" with when using a server and not local machine?

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
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");
});
Think I just solved it. I tried a different port and it worked :/
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();

Using socket io without returning the index.html throws an error

I would like to setup websocket without necessarily having to return the index.html file
Am still new to the socket io and this is what i have tried
installed socket io via
npm install socket.io --save
created index.js
var http = require('http');
var fs = require('fs');
// Loading socket.io
var io = require('socket.io');
// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
console.log('A client is connected!');
});
server.listen(1100);
Now when i run node index am getting an error
io.sockets.on('connection', function (socket) {
^
TypeError: Cannot read property 'on' of undefined
What am trying to do is connect the websocet to my vuejs client side so ive skipped the part to display html part since i dont want to display html but to use the socket events.
where am i going wrong?
Hey you need to attach socket.io to an http server for your code to work and listen to incoming events.
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
//io.on is the shorter form of io.sockets.on
io.on('connection', function(socket){
console.log('user connected');
});

nodejs socket.io GET http://domain/socket.io/?EIO=3&transport=polling&t=LrTVonQ status of 404 when importing socket.io

My problem is simple I'm actually getting an error 404 when I'm trying to import socket.io on my web page. I'm using
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
to import socket.io.
If I remove this line form my head tag, I'm fine but when it's there, I see in the dev tool the 404 error and my counter is not even working.
I am trying to make a live viewer count for one of my website but I never really use Node.js so this is why I have some trouble. Please forgive me if there is an error in my script.
For the serverside script, the file is called: viewercounter.js and this is the code
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = 8001;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
app.use(express.static(__dirname + '/public'));
var count = 0
io.on('connection', function(socket) {
count++;
socket.broadcast.emit('userupd', {
numUsers: count
});
console.log(count);
socket.on('disconnect', function(){
count--;
socket.broadcast.emit('userupd', {
numUsers: count
});
console.log(count);
});
});
Then I placed the clientside script directly in my page instead of making a new file, I did not really see the point of it. Anyway, the file is called: index.php
and the code is at the end of the file just before the end of the body tag and there not other js before the code.
<script type="text/javascript">
$(function() {
var socket = io();
socket.on('userupd', function (data) {
$('.counter').html(data);
});
});
EDIT
By looking more deeper, I've been able to understand that it's a XMLHttpRequest problem. In fact, when the socket.io code that I just imported try to perform xhr.send(this.data) the error appears. Anyone knows how I can solve this ?
https://gyazo.com/53f64081a92b449e157df76c6c570178
EDIT2
After changing the port in the file viewcounter.js. It looks like this:
// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = 80;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
// Routing
app.use(express.static(__dirname + '/public'));
var count = 0
io.on('connection', function(socket) {
count++;
socket.broadcast.emit('userupd', {
numUsers: count
});
console.log('New user: ');
socket.on('disconnect', function(){
count--;
socket.broadcast.emit('userupd', {
numUsers: count
});
console.log('Neg user:');
});
});
If your web page is coming from an Apache web server on port 80 and you want to create a socket.io server in node.js on the same host, then you need to pick a new port for that socket.io server and when you connect to the socket.io server, you need to identify the port you want to connect to because the default will be port 80, but that's not where your socket.io server is.
I'd suggest using port 8001 like you originally had for your socket.io server. Please change your node.js code back to that.
Then, you can change the socket.io code in your page from this:
<script type="text/javascript">
$(function() {
var socket = io();
socket.on('userupd', function (data) {
$('.counter').html(data);
});
});
</script>
to this:
<script type="text/javascript">
$(function() {
var url = window.location.protocol + "//" + window.location.hostname + ":8001";
var socket = io(url, {transports: ['websocket'], upgrade: false});
socket.on('userupd', function (data) {
$('.counter').html(data);
});
});
</script>
This will connect socket.io to the same protocol and host as your web page, but a different port and it will use only a webSocket so you don't run into cross origin issues with socket.io's usual attempt to initiate a connection with Ajax polling.
If your socket.io server is actually on a different host than your Apache server, then you need to put that host in the URL rather than window.location.hostname.

Unresolved function or method on()

This code runs in the server. I am making a simple websocket on the server and it looks for connections made to it. However, IntelliJ does not recognize the on() method that has been called on io. I am using IntelliJ latest version and coding in Node.js
var http = require('http');
var express = require('express');
var socket = require('socket.io');
function onRequest(req,res)
{
console.log('User requested for page: ',req.url);
}
// create a middleware application
var app = express();
app.use(onRequest);
// serve static files
app.use(express.static('public'));
var server = http.createServer(app).listen(4000);
// setup the socket on the server
var io = socket(server);
io.on('connection',function(socket)
{
console.log('Socket id is: ',socket.id);
});
Try npm install #types/socket.io. It will add the necessary definition file.

Categories

Resources