3

I created simple app to start with socket.io, but when I run it, Chrome(tested in other browsers, result same) eats all of my CPU and makes many requests:

enter image description here

I'm new to sockets, but I'm sure this is not how it should work. The code running in browser is really simple, it should just connect to socket and log all received data to console:

index.html

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js" charset="UTF-8"></script>
</head>
<body>
<script type="application/javascript">
    var Sockets = io.connect('http://localhost:4000');
    Sockets.on('Test', function (data) {
        console.log(data);
    });
</script>

</body>
</html>

Also, my server file looks like this:

server.js

var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require("body-parser");
var io = require('socket.io')(http);
var port = 4000;

http.listen(port, function () {
    console.log('Server running at port ' + port);
});

var urlencodedParser = bodyParser.urlencoded({extended: false});
app.post('/', urlencodedParser, function (req, res) {
    if (!req.body) return res.sendStatus(400);
    var post = req.body;
    io.emit("Test", post.data);
    console.log(post.data);
    res.send('true');
});

io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
});

When I run the server node server.js, I got the Server running at port 4000 message and everything seems fine. But when I open the index.html in my browser, the node console is spammed by a user connected messages. Instead of connecting one client, the browser makes dozens of requests every second. When I close the browser, there is no output for some time, and then the node console is spammed by user disconnected messages.

This server should redirect all data sent via POST to connected sockets. When I make this POST request, the node server receives it (I know because it print's it into node console). But it's not received by the socket client, as there is no output in browser console (but the browser still makes dozens of new connections every second.

What is wrong here? First I thought I just messed up, so I went back and copy-pasted code from tutorial I found (not in English, but in Czech), but nothing changed. The tutorial has a lot of positive feedback, so there is propably something wrong with my computer. But what?

Adam Ježek
  • 464
  • 5
  • 15
  • When you say "open the index.html in my browser", what exactly does that mean? Are you opening it directly from the file system? You should be opening it via the web server, not via the file system. Because of the way socket.io connects, it will not work properly to a cross-origin server without CORS configuration on the web server. `http://locahost:4000` will be a cross origin endpoint if you are opening index.html from the file system and will not let you connect properly. – jfriend00 Nov 14 '17 at 23:34
  • @jfriend00 I'm using "Run" button in PhpStorm. As you can see in the screenshot, the url is localhost:phpstorm'sport/somepath/index.html – Adam Ježek Nov 14 '17 at 23:39
  • What does the Run button actually do? I ask again. Is `index.html` being loaded from the file system or from your web server? It needs to be loaded from your web server. FYI, your web server code does not show any way that it is serving index.html so I suspect you are loading it from the file system and that would be wrong and the cause of the problem. – jfriend00 Nov 14 '17 at 23:39
  • @jfriend00 The "Run" button in PhpStorm starts internal webserver in PhpStorm. I can access the page from other computers in my LAN by entering my computer IP with port comfigured in PhpStorm, so there must be a webserver. – Adam Ježek Nov 14 '17 at 23:49

3 Answers3

4

I had experienced the same issue, by following an example where the client was using the source of socket.io from this cdn: https://cdn.socket.io/socket.io-1.2.0.js

Tons of clients created whenever I tried to run the file (no matter if i just double clicked the html file, or if I put it under a web server, like IIS) . I then realized it might be an older version, and I just took the latest one released from this source: https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js

Everything works fine now. Hope this helps

  • Made client and server use same versions of socket.io and it worked! Thanks – Mohsin Dec 21 '18 at 05:56
  • What does this answer mean?? You took it and did what with it? I opened the link and it's just code. Where should I put it? – Chiaro Jul 05 '20 at 00:47
  • @Chiaro the link I have posted is the CDN for socket.io. you need to include it on your app, and code against it. You can find samples of how to create real time communication apps using socket.io google-ing "Real-Time Communications with Socket.IO". choose whatever link works best for you. – Vasile Rusu Nov 02 '20 at 14:11
1

So to find what exactly was wrong, I downloaded example socket chat from socket.io website. When I runned it, I experienced exactly the same wrong behaviour - browser is opening many socket connections every second instead of keeping one.

So I deleted node_modules folder and used npm to install these modules again and whoa, it worked. So propably the files just corrupted during download or whatever it was, but doing the same procedure again was working this time.

Adam Ježek
  • 464
  • 5
  • 15
0

Your configuration of running that page from a different web server than your socket.io server is on won't work as you have it. It will take one of three changes to make it work:

  1. You can use the "same origin" for the web page and the socket.io connection by loading the web page from the same server that your socket.io. That means you need to load the web page directly from your socket.io web server.

  2. You can configure your socket.io web server to accept cross origin connections (CORS connections).

  3. You can configure your socket.io client to connect directly using webSocket without doing socket.io's usual preview with a regular http request.

If you're testing something you intend to deploy for real, you may as well just make your existing socket.io web server server your web page and load the web page directly from that.


Another possible cause of a situation like this is an incompatible client and server version of socket.io. You should make absolutely sure that you have the same version of socket.io on client and server. If you get the client socket.io library from /socket.io/socket.io.js from your socket.io web server, the the client version will automatically always match the server version. The way you are loading it from a CDN, you have to manually make sure you have identical versions.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • I don't think so. The requests are not blocked, the node servers accepts them and in Chrome developer tools, Network tab, they are all listed as 200 OK. For some reason, they are just duplicated many times a second. To make sure, I followed [this question](https://stackoverflow.com/questions/24058157/socket-io-node-js-cross-origin-request-blocked) to enable CORS and it made no difference. – Adam Ježek Nov 15 '17 at 00:02
  • @AdamJežek - Your architecture is just wrong and doesn't mimic anything you'd use in a real world deployment anyway. Fix the architecture and I'm making a big bet that your problem goes away. FWIW, I think this may be a problem introduced in a recent version of socket.io. I've seen several reports of the same type of behavior you report in the last few weeks and never seen one before in 3 years. But, I bet you can avoid it if you use a proper architecture. – jfriend00 Nov 15 '17 at 00:09
  • @AdamJežek - Why do you insist on loading the web page from a server that isn't your actual web server anyway? Just add a route to your web node.js server to load the page and load it through that server. – jfriend00 Nov 15 '17 at 00:11
  • @AdamJežek - I also wonder if this could be caused by a mismatched version of socket.io client and server. I see you are manually linking to a specific client version so you have to manually make sure client and server are the same version. If you load the client from `/socket.io/socket.io.js` from your socket.io web server, then you will automatically get the correct client version of socket.io every time. – jfriend00 Nov 15 '17 at 00:18
  • I was planning to have Apache server that will serve you .php page, that will have included script that connects to socket at node.js server at the same server, only different port. I've seen this at many sites an it's practical. If you have big website running in php, you don't have to rewrite it all in node.js, you just add node.js as second server only for real-time things. I already found solution and it has nothing to do with serving the page, it even works when I open the page from filesystem. – Adam Ježek Nov 15 '17 at 00:36
  • @AdamJežek - So, perhaps it was mismatched versions of socket.io client/server and reinstalling server code fixed things. – jfriend00 Nov 15 '17 at 00:46
  • very unlikely, in both cases I executed `npm install socket.io --save-dev`, nothing to speciffy version in both cases, with just a 2 hours of delay between them. It's much more likely that it was just corrupted during download. – Adam Ježek Nov 15 '17 at 06:19