I'm new in NodeJS and I would appreciate help with duplicate socket writing.
I have the following code in my client part of application and when something happens, I'm sending an alert to the server:
socket.emit('change', {alertType: ALERT_TYPE});
And on the server side I have this:
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
io.sockets.on('connection', function (socket) {
socket.on('change', function (data) {
io.sockets.emit('change-done', data);
});
});
And if more people are using the app I get multiple socket writing like this:
debug - websocket writing 5:::{"name":"change-done","args":[{"alertType":"waiting_delivery"}]}
debug - websocket writing 5:::{"name":"change-done","args":[{"alertType":"waiting_delivery"}]}
debug - websocket writing 5:::{"name":"change-done","args":[{"alertType":"waiting_delivery"}]}
And the number of these sockets writings increases as more people are using this. How can I fix this?
Thank you in advance for your help.
Related
I’m a long term programmer, but haven’t used nodejs much in my code. Now I need to use it in my current code and I’ve ran into a problem that I can’t seem to figure out myself, I have googled a lot but nothing seem to fix it.
I am trying to get my website to connect to the nodejs server running on same host.
If I visit the url in my browser, it works fine (http://localhost:6857/socket.io/?EIO=4&transport=polling) and I see this respond
0{"sid":"s_v860SbNO4toknPAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}
But when I try to connect thru the website, I just get
GET http://localhost:6857/socket.io/?EIO=3&transport=polling&t=N_gL_HZ net::ERR_CONNECTION_REFUSED
Can someone guide my in the right direction for how to fix this, so I can begin using nodejs inside my website?
This is my server.js
// use express
var express = require("express");
// create instance of express
var app = express();
// use http with instance of express
var http = require("http").createServer(app);
// start the server
var port = 6857;
http.listen(port, '0.0.0.0', function () {
console.log("Listening to port " + port);
});
// create socket instance with http
var io = require("socket.io")(http);
// add listener for new connection
io.on("connection", function (socket) {
// this is socket for each user
console.log("User connected", socket.id);
});
io.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
And this is my JS code inside my website
<script>
var server = "http://localhost:6857/";
var io = io(server);
</script>
Socket IO requires you to enable CORS explicitly - Thus why you get the error stated above.
To enable CORS, please see the following link
Hi i have a node js server and im using sockets to communicate.
Index:
<script src="socket.io/socket.io.js"></script>
Client JS:
var socket = io.connect("http://localhost:8081");
socket.on('hi', function(data){
console.log("g");
console.log(data);
});
So it seems to connect just fine to the server. I have a socket called 'hi' waiting for any incoming messages. I added 2 console logs incase data was null, it would still print something to the console.
Server:
var express = require("express");
var app = express();
var server = require("http").Server(app);
var io = require("socket.io")(server);
var mazeGenerator = require("generate-maze");
app.use(express.static("public"));
io.on("connection", function(socket) { // EDITED
console.log("A player has connected - sending maze data...");
socket.emit("hi", "hi");
});
So when i refresh the page, the client connects and in my CMD i see the "A player has connected..." console log. From then on, its blank from the server or client, I can keep refreshing and it will keep saying a player has connected by the clients console stays blank
Since the connection is proven to be established, I suspect this is an issue of a way you emit the data. Your second parameter hi may not be taken as a data to be transmitted, according to
https://socket.io/docs/server-api/#socket-emit-eventname-args-ack
In my understanding, socket.io emit Object instead of String so can you try this?
io.on("connection", function(socket) {
console.log("A player has connected - sending maze data...");
socket.emit("hi", {data: "hi"});
});
Good evening SO-community, I tried really hard to fix this issue but I think I'll need your wisdom because I really don't know what's the matter here. I have a node.js server which is serving an index.html via express. I am currently starting to use socket.io.
This is the code on my client side:
$( document ).ready(function() {
document.getElementById("start").addEventListener("click", startGame);
function startGame() {
var socket = io(); console.log("Sending request to server");
socket.emit('connectToTable', {tableID: 1});
socket.on('successfulConnection', function(msg){
alert(msg);
}); }
});
This is the code on my server side:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require('express');
var port = process.env.PORT || 3000;
path = require('path');
app.use(express.static(path.join(__dirname, '/')));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("There is someone knocking on the door")
socket.on('connectToTable', function(socket){
console.log("Received player request")
var player = new Player(socket.id);
socket.emit('successfulConnection', "The connection to the server has been successful");
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
On my console on the server I see that "There is someone knocking on the door" gets printed hundreds or thousands of times per second which leads to a CPU load of 100%. At the same time I can see on the client-side (in Chrome) that hundreds of xhr polls are being made.
I really can't figure out why the connection is not established after the first connection attempt and retried sooo often. Furthermore I don't even really understand why it is even using xhr polling instead of websockets.
Help would be very highly appreciated. Thank you so much in advance.
You have to use the same version of socket.io, on the client and on the server (I have had the same problem 5 days ago), check on console with:
npm list socket.io
the version of the server and look if you use the same version on the client, on index.html like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
You can get the url from here:
Versions of socket.io
Regards
I have a NodeWebkit client which connects to a nodejs server using the socket.io library (JavaScript).
The client launches the connect procedure on the application start but the server does not acknoledge any connections... Though the client's socket has the connected attribute to "true".
You should know that I am using socketio-jwt to authentificate the connection.
Github: https://github.com/auth0/socketio-jwt
I know that the connection does work in a way because if I add :
io.sockets.on('connection', function(){console.log("hello");})
It prints hello !
So it seems that event though the connection is somehow made it doesn't want to do the auth part with the library, resulting in... Well... Nothing.
But that's not all !!
Because if I reboot the app (not the server) then the auth works most of the time ! It acts like a race condition... But I dont see how it could possibly be one... Every line of code is geting executed appart of the success callback of authentification.
I tried connecting to a remote server and on my localhost.
I also tried with an other library of socket auth but I've got the same probleme.
This is the server code:
var session = require('express-session');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketioJwt = require('socketio-jwt');
io.sockets.on('connection', socketioJwt.authorize({
secret: 'some secret',
timeout: 15000 // 15 seconds to send the authentication message
})).on('authenticated', function (socket) {
console.log('[Info]: A user connected to socket = ', socket.decoded_token);
});
});
http.listen(5000, function () {
console.log('listening on *:5000');
});
And now the client code:
this.socket = io.connect('http://' + that.hostName +':' + that.port);
var token = jwt.sign({email: "someEail", pwd: "somePwd"}, fromServerSecret);
this.socket.on('connect', function () {
that.socket.emit('authenticate', {token: token}) //send the jwt
.on('authenticated', function () {
console.log("[Info]: Socket login successfull");
})
.on('unauthorized', function (msg) {
console.log("[Warning]: Socket unauthorized: " + JSON.stringify(msg.data));
throw new Error(msg.data.type);
});
});
The server side log "A user connected to socket" is never shown.
If you have an idear ! Thanks for your time.
Why is there a 'that' on socket.emit (client)? I think you should handle it within the same instance of socket.io - using same 'this' as above
I just started up learning how to make web applications. I am making a webserver in nodejs (a to-do list app). I am using the express framework, and mongodb as database. For communication between the client and the server i am using socket.io.
I can't find a way to make it so that when the server emits and event the client will update the info on all of his open windows of the page. Right now the info updates only on the window that triggered the event on ther server. This is the server code:
Server code:
var io = require('socket.io').listen(server);
io.of('/home').on('connection', function (socket) {
socket.on('newListGroup', function (data) {
...
socket.emit('groupNo', obj);
});
}); `
Client javascript:
var socket = io.connect('http://localhost/login');
socke.on('groupNo', function(data){ ... });
$('#newListGroup').blur(function() {
socketLogin.emit('newListGroup', {newGroup:newGroup});
});
Can this work or should I take another approach?
You can broadcast a message to all sockets like this:
var io = require('socket.io').listen(server);
io.of('/home').on('connection', function (socket) {
socket.on('newListGroup', function (data) {
socket.broadcast.emit('groupNo', obj); });
});
It should be limited to the namespace but you will probably have to implement your own logic for broadcasting only to windows on the same client (probably using authentication) if that is what you want to do.