Problems using socket.io, socket.io.js not found - javascript

I receive this error in console GET http://localhost/socket.io/socket.io.js 404 (Not Found). I used npm install to install express and socket.io. Everytime I try to access localhost:3000 it downloads a file instead of displaying chat.php
This is my javascript code
var express = require('express')
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
users = [];
connnection = [];
console.log('Server running!');
app.get('/',function(req, res){
res.sendFile(__dirname + '/game.php');
});
io.sockets.on('connection', function(socket){
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
//Disconnect
socket.on('disconnect', function(data){
connections.splice(connections.indexOf(socket),1);
console.log('Disconnected: %s sockets connected', connections.length);
});
});
And this is what I added into php file
<script src="/socket.io/socket.io.js"></script>
<script>
$(function(){
var socket=io.connect();
});
</script>

res.sendFile(__dirname + '/game.php'); just sends a raw PHP file to the browser client. Instead, what you need to send to the browser is HTML. So, you either have to change your app to run in node.js and not PHP or you have to exec that PHP file and grab its output and send that to the browser.
Normally, if you wanted your page to be generated via PHP, you wouldn't be using node.js at all - you'd just be using PHP. If the only reason you brought node.js into the equation is because of socket.io, then maybe you should be using socket.io directly with PHP which you can read about in this question. You could use a hybrid of node.js and PHP, but it's unlikely to be all that efficient if you're using node.js to run your PHP. For that case, you would probably be better off running socket.io in node.js on a different port number, enabling cross origin access and just leaving your PHP to be PHP.

I found the working solution with PHP here https://github.com/jdutheil/nodePHP. I tested it and it is working just great.

Related

Why socketIO call too much connections?

I created my Socket server with Express, SocketIO and Redis
server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8890, function (e) {
console.log(e);
});
io.on('connection', function (socket) {
console.log("new client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
console.log("mew message in queue "+ message + "channel");
socket.emit(channel, message);
});
socket.on('disconnect', function() {
redisClient.quit();
});
socket.on('connect_error', function() {
redisClient.quit();
});
});
From command line, I run node server.js. Its worked.
I also created a html file to connect to that server.
From Browser Console, I run io.connect('http://localhost:8890'). I got as the result
As I see, too much connections (requests).
What happens? What wrong from my code?
You have mismatched client and server versions causing the initial connection to fail and the older client is dumb enough to just keep trying over and over again. If you are using 2.0.4 on the server, then you must use that version for the client too. If you serve the client version directly from your server with:
<script src="http://localhost:8890/socket.io/socket.io.js"></script>
Then, the socket.io server will automatically give you the right client version.
Or, you can manually link to the right version on your CDN such as https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js. But client and server versions MUST match.
The advantage of getting the client directly from your own server is that anytime you update your server version of socket.io, the client version will automatically be upgraded for you and kept in perfect sync since the matching client version is built into the server version.

How to include node.js to static html

I'm trying to do API in javascript for another users. I want to create a chat in realtime in Node.js with socket.io but I want to give the opportunity loading this API in common HTML through javascript. For example, if somebody copy and paste simple js script into your html, then chat is loaded.
My app is running in node on port 8080 and my other page is html on port 80.
How can I put node.js in other page?
below is my chat.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var cors = require('cors');
app.use(cors());
app.options('*', cors());
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('chat message', function(msg){
console.log('the user wrote:' +msg);
io.emit('chat message', msg, id);
});
});
http.listen(8080, function(){
console.log('listening on *:8080');
});
In this way I try to load:
<script>
$.ajax({
xhrFields: {
withCredentials: true
},
dataType: "html",
url: "http://127.0.0.1:8080/index.js"
}).done(function(data){
// next function here;
});
</script>
You don't "include node.js", what you need to do is include the script that connects to the server via socket.io (8080 server).
This post may be useful for you http server and web sockets from separate servers.
On the other hand, you can include client side javascript from the 8080 server in order to make the chat run correctly.
Edited for more details.
In the server running on 8080 you can create a server with Socket.io and Express, there you can have the server side logic of your chat and serve the JavaScript file with the client side logic. Let's say, the client JavaScript file is located in http://localhost:8080/yourchat.js (of course, in some sort of real world you may have to generate this file in order to emit data to the correct users)
In the server running on 80 you'll have your div element and a script tag with this source: http://localhost:8080/yourchat.js. Using this pattern you sould be able to embed the chat

Socket.io initialization resulting in a 404 network error

I am using nodejs and express to create a basic chat app and I'm getting a network 404 error message when trying to initialize the socket.io object.
<script src="/javascripts/socket.io/socket.io.js-client"></script>
<script type="text/javascript">
var socket = io.connect();
</script>
Tha above code results in a 404 error for some polling call
"NetworkError" 404 Not Found - http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1432851505880-89
I need the polling to run using the following url instead: http://localhost:3000/javascripts/socket.io/?EIO=3&transport=polling&t=1432851505880-89
because I am using express, but not sure how to accomplish this.
Server Side Code:
var app = express();
var server = require( "http" ).createServer( app );
var io = require("socket.io").listen(server);
server.listen(8888);
io.sockets.on('connection', function(socket){
socket.on('send message', function(data){
io.sockets.emit('new message', data);
});
});
module.exports = app;
I have been trying to troubleshoot this one for quite a while now with no success. I appreciate any advice. Commenting out the var socket = io.connect() resolves the error. Appreciate any advice.
Thanks
Your web page is apparently running on port 3000, but your socket.io server is listening on port 8888. The two must be the same port so it is no surprise that there is no response for a socket.io request on port 3000 (since your socket.io server is listening on port 8888).
Because the default URL it is trying is port 3000, then that must be the port that your web page is one and it must be served by a different web server. If that is the case, then you will need to do one of two things:
Combine the web server that serves your web pages with the socket.io server so the same server is taking care of both.
Specify the port in the client request and enable your socket.io server for cross-origin requests.
To specify the port in the client request, you can do this:
<script src="http://myserver.com:8888/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io("http://yourserver.com:8888");
</script>
Note, that this is requesting the client socket.io library from the express server where your socket.io server is (so it's using the same port that your socket.io server is running on).
If the HTML where socket.io client javascript is being served is not also being served by express at port 8888 (it looks like the html is coming from port 3000), you may just need to configure the socket.io client to point at the port where the server-side socket.io has been setup to listen (8888):
var socket = io.connect('localhost:8888');

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