socket.io - hundreds of requests instead of one connection - javascript

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:
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?

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

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.

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:
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.
You can configure your socket.io web server to accept cross origin connections (CORS connections).
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.

Related

Socket IO keeps disconnecting and reconnecting

I'm very very new to sockets and socket.io, so I apologize if this is an obvious question. I'm using the C# client for Socket.IO and have a local javascript server running. Here is my app.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('test', function () {
console.log('Test run'); });
socket.on('disconnect', function () {
console.log('A user disconnected'); });
});
http.listen(3000, function() {
console.log('listening on localhost:3000'); });
In my main C# class (it is a Windows Forms application) the only line of code I have relating to the sockets at all is the instance variable private Socket socket = IO.Socket("http://localhost:3000/");. Yet for some reason, the server repeatedly receives the connect and disconnect events. Here is a screenshot of my console:
screenshot
This all happens automatically, as soon as I run my C# program, without any interaction, and stops as soon as I close it. Any ideas as to why it keeps connecting/disconnecting?
EDIT: For whatever reason the problem seems to go away when I remove Newtonsoft.json from the project. However, without it I cannot use the Emit function as well as others. Is there a workaround to this?
To anyone encountering this issue, check if client & server speak the same protocol version.
On a high-level, this is likely to be caused by protocol version mismatch between server and client. I've had the same issue in JS app. Turned out I was using some older version of socket.io on the client and the latest on the server. In the repository you provided we can find:
// EngineIoClientDotNet/Src/EngineIoClientDotNet.mono/Parser/Parser.cs
public static readonly int Protocol = 3;
So this (now deprecated) client is using Engine.IO protocol v3. You didn't provide info which socket.io version you were using on the server, but it simply might've been using different revision on Engine.IO protocol.
As a side note, speaking more low-level: I guess that the client might be able to connect, but it does not respond to server's first ping command in a proper way (or the other way around). Therefore the connection is immediately dropped. Socket.IO has a history of breaking changes in how ping-pong mechanism is implemented, and this might be the underlying root cause.

socket.io confusion with express.js

server side code:
var server = require("http").Server(express);
var io = require("socket.io")(server);
server.listen(5000);
io.on('connection', function(client) {
client.on('order', function(data) {
io.emit('place_order',data);
});
});
cilent side code
var socket = io.connect('http://localhost:5000');
socket.on('place_order', function (data) {alert('data.x')})
Somewhere in github I git clone a project and I saw something above. The 3rd line of server side code confused me. Why the author created extra port here? isn't it ok to discard the 3rd line and in the cilent side just connect to the path without port like var socket = io.connect('http://localhost:5000');? Need explanation for socket.io expert here, I'm confused.
btw this code does work..
Why the author created extra port here?
You have to start your server on some port and server.listen(nnn) is one way to do that. If you don't start your server, it isn't actually running and you can't ever connect to it.
Servers must be created and then started on a specific port.
In your particular code example, you've chosen to run your server on port 5000 instead of the more common port 80.
isn't it ok to discard the 3rd line
No. Without it your server will not be running.
If your server is started on port 80, then you don't have to list a port number in the URL since that is the default port number for an http:// connection.
After attaching your socket.io to an HTTP server, it needs to start. This how socket works. Thats what the 3rd line does. So, removing it means you are not starting the server itself, and obviously that wouldn't work.
The port is at 5000 which might look unconventional to you, but this is a standard practise to prevent errors if the PORT 80 is in use, like it often is by other web/internet based applications/servers. But, if that isn't the case feel free to change the port to 80 by replacing the 3rd line as server.listen(80);
For Ref: if you get the error: Error: listen EADDRINUSE :::80 then understand directly that the port wasn't free!!
That is not a socket.io's problem. In a Node.js application you need to specify which port do you want your Node.js runs.
Node.js is a plataform and in the first line you create a server and for that you need to put the port that your server runs.
https://nodejs.org/dist/latest-v6.x/docs/api/http.html#http_http

Node.js example not working on Windows 10

I'm trying to begin the backend of a MEAN project I'm working in right now. It's a project for testing purposes, and Node is still in my TO-DO list.
So, I today wrote this simple server to have something to begin with, and at least being able to see my Angular page and begin to create a simple server-side API. The example can be seen in many websites:
//Lets require/import the HTTP module
var http = require('http');
//Lets define a port we want to listen to
const PORT=8080;
//We need a function which handles requests and send response
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});
Well, the problem is quite simple: when I try to access to localhost/myproject, it just doesn't work. Happens the same for 127.0.0.1/myproject. The js file is in the same folder than the project folder, so I should be able to access this way if the server were working.
I looked for an already answered question and found one in which you have to deactivate a directive in Windows Firewall... but that directive doesn't exist in mine.
So, any help with this?
Please add port 8080 to your access url 127.0.0.1:8080/myproject.

Prevent other people from emitting socket info

I have my node socket server running on the same VPS as my website is. Is there a way I can prevent other "websites" or other node projects from connecting to my socket server and emitting data?
My website and node project have the same IP address.
For example: (client side html)
<script>
var socket = io.connect('localhost') //localhost as an example
socket.on('example', function(data) {
console.log(data) ;
});
socket.emit('sendToServer', 'hello world');
</script>
I want this code right here to only be usable by my website (or IP)
EDIT: If there isnt any to do this within socket.io, is there a way I can authenticate my socket server to make it so only my IP can emit things
If you're that concerned about it, you should consider only allowing authenticated users. Otherwise trying to ban explicit IP addresses and maintaining that list isn't very feasible.

WebSocket not connecting to socket.io

I am using Node.js with socket.io to implement websockets in one of my pages. server.js (what Node.js runs) has this code:
var http = require("http").createServer(),
io = require("socket.io").listen(http);
http.listen(8080);
io.sockets.on("connection", function(socket) {
socket.emit("message", {hello:"world"});
});
And this is the code I'm trying to connect with:
var socket = new WebSocket("ws://92.60.122.235:8080/");
socket.onopen = function() {
alert("Socket has been opened!");
}
When I load the page, nothing happens. I'm using Chrome, and I know websockets are supported. No errors are present in the error console, and if I watch socket.io serving requests from command line I don't see any user connecting.
As far as I know this should work, could anyone explain what could be going wrong?
You need a socket.io client to pass some authentication phases I believe. Try this, and it should work(the client javascript is served by socket.io itself, don't worry about it).
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('message', function (data) {
console.log(data);
socket.emit('helloworld', { msg: 'why do you so love to say hello world?' });
});
</script>
From http://socket.io/#faq
Why not just call it WebSocket if the actual WebSocket is not
present and mimick its API?
Socket.IO does more than WebSocket, even
if WebSocket is selected as the transport and the user is browsing
your website with an ultra modern browser. Certain features like
heartbeats, timeouts and disconnection support are vital to realtime
applications but are not provided by the WebSocket API out of the box.
This is akin to jQuery's decision of creating a feature-rich and
simple $.ajax API as opposed to normalizing XMLHttpRequest.
You can download the webpage source code that runs in Chrome, Firefox, and IE (at least) via the blog article "Websocket Server Demonstration" from the High Level Logic Project. The webpage is set up for developers.

Categories