Issues with using Socket.io - javascript

I am trying to use socket.io for the first time, Im using it with a MEAN Stack. I have set it up the following way.
Server.js
var express = require('express');
var app = express(); // create our app w/ express
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.listen(port);
io.on('connection', function(socket) {
socket.emit('message', {
'message': 'hello world'
});
});
HTML File
<script>
var socket = io.connect();
socket.on('message', function(data) {
console.log(data.message);
});
</script>
I couldn't find the socket.io.js file so I searched for a CDN for the script. I used the following.
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.js"></script>
I tried downloading the socket.io.js from their website but the website seems to be down. I can access it, I get the 502 BAD GATEWAY error (http://socket.io)
When I load my HTML page after setting everything up as shown above I get the following error in the console.
Any help will be greatly appreciated!
UPDATE:

The socket.io server will perform some magic to provide that file when you retrieve it like this:
<script src="/socket.io/socket.io.js"></script>
EDIT: ah, I see the problem: your Express setup is incorrect.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.listen(port);
You're attaching socket.io to a server created by http.createServer, but with app.listen() you're actually creating a new server, one that socket.io isn't attached to.
You can make the setup a bit simpler:
var express = require('express');
var app = express();
var server = app.listen(port);
var io = require('socket.io')(server);
No need to use http.

As of now, socket.io website is still down. If you don't have the file in your server, it does not help using /socket.io/ because this points to a route on your server and that route doesn't seem to exist on your app. With this config, you need to be serving the .js file statically from your server - but I don't see that on your server code.
When you try the CDN, make sure the file is being loaded.

Related

Express and node.js run from a folder; all links point to url root

I have installed node inside a folder and am forwarding it through apache. I am doing this because I have several virtualhosts run through apache, and I do not want to take the time to set up everything through node.
Apache and Node.js on the Same Server
However, I am trying to create a chat engine. I try to include some js files, but they search for http://example.org/myscript.js instead of http://example.org/chat/myscript.js
I got around this by using
<base href="/chat/">
However, now I am trying to integrate socket.io. I included socket.io from https://cdn.socket.io/socket.io-1.3.5.js because I could not get the locally serverd /socket.io/socket.io.js to properly be located.
Now socket.io is trying to connect to http://example.org/socket.io
That dierectory does not exist. If anything, the proper path should be http://example.org/chat/socket.io
I have been looking all over the internet for a solution. There must be something fundamental or obvious about how nodejs/express operates that I am missing. Thanks a million!
Server.js - This is the file I start with node.
var express = require('express');
var path = require('path');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io').listen(http, { log: true, resource:'/socket.io/'});
app.use('/socket.io', express.static(path.join(__dirname,'/node_modules/socket.io/lib/')));
app.use('/bootstrap', express.static(path.join(__dirname,'/node_modules/bootstrap/dist/')));
app.use('/', express.static(__dirname));
var server = app.listen(8000);
io.sockets.on('connection', function(socket) {
console.log('A user connected!');
})

Socket.io with two node.js servers?

I am a confused how to use socket.io so that two node servers can emit events between each other.
Server.js localhost:9200
io.sockets.on('connection', function(socket) {
socket.on('messageFromClient', function(data) {
socket.broadcast.to(data.chatRoom).emit('messageFromServer', data);
});
});
This socket connection listens to the server like so
var appPort = 9200;
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
// Launch server
server.listen(appPort);
I have a website being served by node.js... Server.js localhost:3000: I need this to be able to receive and emit events from localhost:9200
How do I setup server.js for localhost:3000?
I figured this out, it's really quite simple. There can be two node servers, but only one server needs to use socket.io and handle the events. All you need to do to connect is share the client side script via CORS, I wanted to avoid CORS, but you only need to share the socket.io script over CORS and nothing else, so it's not so bad.
First thing needed is to allow your other domain to access the script via CORS.
// requires cors module I think (var cors = require('cors');)
var corsOptions = {
origin: 'http://localhost:3100',
credentials: true
};
Then secondly, it's important client side to use io.connect I am not sure if that was depreciated or something but none of the modern docs mention this.
// What worked for me
var socket = io.connect('http://localhost:3100');
// Docs say
var socket = io('http://localhost:3100'); // ?? I am not sure why but io.connect worked for me.

How to include JS file in HTML, using NodeJS Express server?

I'm creating a chat, using server Express of NodeJS and AngularJS for manager in client side
But when I try include /js/code.js in my html, it can not found, because is not routed by Express
<!-- my include in html -->
<script src="./js/code.js"></script> <!- this is not found in execution -->
Meu index.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require("socket.io")(http);
app.get('/', function(request, response){
response.sendFile(__dirname + '/index.html');
});
How to can I fix this problem, without route all js file I will using in my project or routing all js file in path a lot?
Use app.use to specify your public files to your node app, like below
app.use(express.static(yourPublicPath));
EDIT:
You are getting "Express undefined" error because it is not defined. You can easily fix this by defining your app in 2 stages:-
var express = require('express');
var app = express();
On a side note, I would strongly recommend to go through Expressjs docs to learn more about Express.

node.js /socket.io/socket.io.js not found

i keep on getting the error
/socket.io/socket.io.js 404 (Not Found)
Uncaught ReferenceError: io is not defined
my code is
var express = require('express'), http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
and
<script src="/socket.io/socket.io.js"></script>
what is the problem ???
any help is welcome!
Copying socket.io.js to a public folder (something as resources/js/socket.io.js) is not the proper way to do it.
If Socket.io server listens properly to your HTTP server, it will automatically serve the client file to via http://localhost:<port>/socket.io/socket.io.js, you don't need to find it or copy in a publicly accessible folder as resources/js/socket.io.js & serve it manually.
Code sample Express 3.x -
Express 3 requires that you instantiate a http.Server to attach socket.io to first
var express = require('express')
, http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
//...
server.listen(8000);
Happy Coding :)
How to find socket.io.js for client side
install socket.io
npm install socket.io
find socket.io client
find ./ | grep client | grep socket.io.js
result:
./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js
copy socket.io.js to your resources:
cp ./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js /home/proyects/example/resources/js/
in your html:
<script type="text/javascript" src="resources/js/socket.io.js"></script>
It seems that this question may have never been answered (although it may be too late for the OP, I'll answer it for anyone who comes across it in the future and needs to solve the problem).
Instead of doing npm install socket.io you have to do npm install socket.io --save so the socket.io module gets installed in your web development folder (run this command at the base location/where your index.html or index.php is). This installs socket.io to the area in which the command is run, not globally, and, in addition, it automatically corrects/updates your package.json file so node.js knows that it is there.
Then change your source path from '/socket.io/socket.io.js' to 'http://' + location.hostname + ':3000/socket.io/socket.io.js'.
... "You might be wondering where the /socket.io/socket.io.js file
comes from, since we neither add it and nor does it exist on the filesystem. This is
part of the magic done by io.listen on the server. It creates a handler on the server
to serve the socket.io.js script file."
from the book Socket.IO Real-time Web
Application Development, page 56
You must just follow https://socket.io/get-started/chat/ and all will work.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, function(){
console.log('listening on *:3000');
});
If you are following the socket.io tutorial https://socket.io/get-started/chat/, you should add this line as below.
app.use(express.static(path.join(__dirname, '/')))
This is because in the tutorial, Express will only catch the url
/ and send the file of index.html.
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
However, in the index.html, you have a script tag (<script src="/socket.io/socket.io.js"></script>) requests the resouce of socket.io-client, which is not routed in index.js (it can be found in console-network that the url is http://localhost:3000/socket.io/socket.io.js).
Please check the directory path mentioned in your code.By default it is res.sendFile(__dirname + '/index.html');
make sure you index.html in proper directory
Steps to debug
npm install socket.io --save in static files (index.html) for example, you may have installed it globally and when you look at the debugger, the file path is empty.
Change your script file and instantiate the socket explicitly adding your localhost that you have set up in your server file
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
<script>
const socket = io.connect("localhost:5000");
$(() =>
Double check that the data is flowing by opening a new browser tab and pasting http://localhost:5000/socket.io/socket.io.js you should see the socket.io.js data
Double check that your server has been set-up correctly and if you get a CORs error npm install cors then add it to the server.js (or index.js whatever you have chosen to name your server file)
const cors = require("cors");
const http = require("http").Server(app);
const io = require("socket.io")(http);
Then use the Express middleware app.use() method to instantiate cors. Place the middleware this above your connection to your static root file
app.use(cors());
app.use(express.static(__dirname));
As a final check make sure your server is connected with the http.listen() method where you are assigning your port, the first arg is your port number, for example I have used 5000 here.
const server = http.listen(5000, () => {
console.log("your-app listening on port", server.address().port);
});
As your io.on() method is working, and your sockets data is connected client-side, add your io.emit() method with the callback logic you need and in the front-end JavaScript files use the socket.on() method again with the call back logic you require. Check that the data is flowing.
I have also edited a comment above as it was the most useful to me - but I had some additional steps to take to make the client-server connection work.
If you want to manually download "socket.io/socket.io.js" file and attaché to html (and not want to get from server runtime) you can use https://cdnjs.com/libraries/socket.io
like
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js" integrity="sha512-eVL5Lb9al9FzgR63gDs1MxcDS2wFu3loYAgjIH0+Hg38tCS8Ag62dwKyH+wzDb+QauDpEZjXbMn11blw8cbTJQ==" crossorigin="anonymous"></script>
while this doesn't have anything to do with the OP, if you're running across this issue while maintaining someone else's code, you might find that the problem is caused by the coder setting io.set('resource', '/api/socket.io'); in the application script, in which case your HTML code would be <script>type="text/javascript" src="/api/socket.io/socket.io.js"></script>.
If this comes during development. Then one of the reasons could be you are running a client-side file(index.html). But what you should do is run your server(example at localhost:3000) and let the server handle that static file(index.html). In this way, the socket.io package will automatically make
<script src="/socket.io/socket.io.js"></script> available on the client side.
Illustration(FileName: index.js):
const path = require('path');
const express = require('express');
const socketio = require('socket.io');
const port = 3001 || process.env.PORT;
const app = express();
const server = http.createServer(app);
const io = socketio(server);
//MiddleWares
app.use(express.json());
app.use(
express.urlencoded({
extended: false,
})
);
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile('index.html');
});
io.on('connect', (socket) => {
console.log('New user joined');
}
server.listen(port, () => {
console.log(`App has been started at port ${port}`);
});
After this run your server file by the command
node index.js
Then open the localhost:${port}, Replace port with given in the index.js file and run it.
It solved my problem. Hope it solves yours too.

Node.js socket.io.js not found or io not defined

I'm trying to run a node.js application on my freebsd server, but I can't get the socket.io library to work with it. I've tried including:
<script src="/socket.io/socket.io.js"></script>
Which gives a 404 error, and if i link directly to the file (i.e. where it is in my public_html folder) I get the io not defined error.
Thanks in advance
Try creating another node.js application that has this single line in it and then run it with node.js
var io = require('socket.io').listen(8000);
Then in your browser visit http://127.0.0.1:8000 and you should get the friendly "Welcome to socket.io." greeting. If you are getting this then socket.io is running and will serve the socket.io.js file.
The only other thing that I can think of that might be happening is that you might not be linking to the alternate port in your client file. Unless you're running the socket.io server on express which is running on port 80. For now create a client file that has the script source for socket.io set to
<script src="http://127.0.0.1:8000/socket.io/socket.io.js"> </script>
This should connect to the socket.io server running on port 8000 and get the socket.io.js file.
Your node.js application still has to serve it - it does not get served automagically. What do you have in your server? It should be something like
var app = require('express').createServer();
var io = require('socket.io').listen(app);
or similar (the listen is important). The location is not a real location on the disk - socket.io library should intercept the URL and serve its clientside library, as far as I understand.
Add the following after body parser:
, express.static(__dirname + "/public")
So something like:
var app = module.exports = express.createServer(
express.bodyParser()
, express.static(__dirname + "/public")
);
For those who got the same kind of issue if they run (open) your html file directly from your local file directory(ex: file:///C:/Users/index.html).
Solution: You have to run(open) the file through localhost (ex: http://localhost:3000/index.html) where the server is listening to.
Below code snippet shows how to create a server and how to wire together with the express and socket.io
const express = require("express");
const app = express();
const httpServer = require("http").createServer(app);
const io = require("socket.io")(httpServer);
///////////////////////////////////////////////////////////////
// Any other server-side code goes here //
//////////////////////////////////////////////////////////////
httpServer.listen(3000, () => {
console.log(`Server listening to port 3000`);
});

Categories