socket.io-client and webpage - node.js

This is probably a very simple thing, but I can't figure it out as I'm relatively new to this. I have a server with an index.html page running great on nodejitsu. It works fine with no issues at all. However, I also have another node.js utilising socket.io-client. It's connecting fine and doing what I want it to do, but I'd like to incorporate an HTML page with it so I can control it with a click of a button. Essentially, I am trying to get my nodejitsu server page to refresh with a click of a button on my socket.io-client page. Here's the code on my client:
var io = require('socket.io-client'),
socket = io.connect('http://danturner81.server.jit.su', {port: 80});
socket.on('connect', function () { console.log("socket connected"); });
socket.on('disconnect', function () { console.log("socket disconnected"); });
socket.send('refreshScreen');
When I start this node via the terminal, it refreshes the page at danturner81.server.jit.su just fine. How would I incorporate this into a webpage with a button that executes the 'socket.send'?
Sorry if this appears dumb, but I really can't figure it out and I know I'm close to getting where I want!
Regards
Dan

Related

Dynamically update data on webapp without refresh

I have created a webapp that was working fine as a standalone app without the need of nodejs or anything, but now I am trying to migrate it to Expressjs/nodejs.
The problem that I am having right now, is that I want to be updating the data on that website dynamically, in realtime without the user having to refresh the webpage. The webpage is basically just showing some values, and they need to refresh every half a second or every second to make it appear realtime.
First I started off with EJS, but I couldnt find a way to do this with EJS and most answers that I found pointed out that I have to use something like socketIO to get this done and so I did.
My socketIO code on the server:
io.on('connection', (socket) => {
setTimeout(function() {emiter(socket)}, 1000)
console.log('a user connected');
});
function emiter (socket) {
socket.emit('MyEvent', GetData.RData.R[" 1"].Val);
}
My socketIO code on the front end:
var socket = io.connect('http://192.168.0.2:3000')
socket.on('MyEvent', function (message) {
$("#test").html(message);
})
It is sending the data, but it is not refreshing when new data is available.
GetData.RData.R is being populated by an ajax call that is executed every 1 second to retrieve new data from a device.
If I manually refreh with F5 new data is displayed.

socket.io - .on not working on client side

I have some very basic code that uses socket.io
Client
var socket = io();
// Do some stuff...
socket.emit('hello', 'please like me');
// Wait for a response
socket.on('hello back!', function(msg) {
console.log('Yay, he replied:', msg);
});
Server
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('disconnect', function() {
console.log('user disconnected');
});
socket.on('hello', function() {
// Code to decide wether or not I like the client
// ...
// I do like the client!
socket.emit('hello back!', 'how are you');
console.log('I said hello back!');
});
});
Hopefully you managed to get the picture. So ideally, this would happen:
Client connects
After a while, client emits hello
Server sees this, emits hello back!
Client notices the hello back! event
Everyone is happy!
But this isn't the case for me unfortunately. Instead, steps 1-3 work perfectly. But when you reach step 4 and 5, things start to fall apart. Client never logs anything after hello back! event is emitted.
This is not my full code, I figured it would make it easier for you to understand it. It's very possible that I've made some silly mistake somewhere, maybe without including it in this code. But please let me know if there is anything fundamentally wrong with what I am doing.
Cheers
This is a few years old, but in case anyone stumbles across this in the future:
My problem had nothing to do with my code shown above. Instead, it was a configuration error.
I was hosting my project on glitch.com who state that they support websockets, but the error was caused because the server was not able to get across to the client (client never received any data from server at all after websocket connection was opened).
This was an error that I had in 2018 with glitch.com, and I know that other people have had it too. It also seemed to be related somehow to websockets connecting via a domain name and with SSL, but I can't recall the exact circumstances.

Double connection in Socket.io

My question is very simple. I have a Node.js server with the following code
io.on('connection', function (socket) {
console.log('connection');
});
My web page contains just
var socket = io();
I open the app in one window. Then I open it in another. The console shows three connections. If I refresh one of the windows, the console shows a total of six connections. I refresh once more, I get 10 connections. Once more, 15 connections.
How is that possible? I would like one connection per page load, how can I achieve that.
Thanks for your attention!
NB: I don't know if it is important, but I am also using Express, Mysql and sessions
I had to put the io.on() outside my app.get().
i had same problem instead of io.on('connection')
just use
io.once('connect')
EDIT: here is code
io.once('connect', function (socket) {
console.log('connection');
});

Using Meteor and socket.io together

I am newbie about Meteor.
I am developing a realtime multiplayer game. I want to implement everything about the game but game engine states with Meteor. For example chat messages, available game rooms, invitations, online members etc. I want to make those functionalities withMeteor.
But I want to implement game states manually without Meteor with socket.io. Because, the game is real time and every 45 msec(in my architecture), game states will be streaming to the clients and I think Meteor is not for this and not flexiable. So I developed multiplayer concept and synchronising clients and server with socket.io. There is no problem about it.
I want to use Meteor and socket.io both and together. I tried to implement it. I installed socket.io with npm inside .meteor/local/build/programs/server/app under my meteor app. After that I include require statement on server side Meteor startup;
Meteor.startup(function () {
var require = Npm.require;
var sio = require('socket.io')
var socketIO = sio.listen(this.http)
socketIO.configure(function () {
socketIO.set('log level', 0);
socketIO.set('authorization', function (handshakeData, callback) {
callback(null, true); // error first callback style
});
socketIO.set("transports", ["xhr-polling"]);
socketIO.set("polling duration", 30);
});
socketIO.sockets.on('connection', function (client) {
console.log(client.id + ' is connected')
client.on('disconnect', function () {
console.log(client.id + ' is diconnected')
});
})})
And I put the connection statement on client side Meteor startup;
Meteor.startup(function () {
socket = io.connect();
socket.on('connect', function () {
console.log('connecting');
});
})
On client side, io variable is not defined error is occurred. This is seen to me that,Meteor does not import client side socket.io.js on client side. So I tried to put socket.io.js manually under clients folder to load it on client side. This is not good way I know, I should not do this. But, even I do and client loads it, there is another client side error about transport variable of io for the statement;
io.transports.push('xhr-polling');
It says that Uncaught TypeError: Cannot call method 'push' of undefined. Somehow, client side socket.io.js can not be loaded properly.
I could not find an example for usage of Meteor and socket.io together. Is there a simple way to use them both together?
Thank you!

emitting data via socket on browser close /window close

I need to send data to nodejs server via socket.io when the user closes the browser tab .
I tried doing :
var data={};
window.onbeforeunload = function() {
// i have a object to be sent
data.data1='abcd';
data.data2=1234;
socket.emit("senddata",data);
}
This code works when the user navigates around clicking links on the site but doesnot work when the user closes the browser tab
I also tried configuring the socket io on server side as below .. thinking the error may be due to socket connection being closed before emitting data:
var io = require('socket.io').listen(app.listen(port));
io.configure(function () {
io.set('close timeout',12000);
});
It also didnt work most of the time.
I also tried this on client side:
var socket = require('socket.io').listen(80, {
"sync disconnect on unload":false
});
It also did not work
I had tried receiving data like this
var io = require('socket.io').listen(app.listen(port));
io.sockets.on('connection', function (socket) {
socket.on('senddata', function (data) {
// data processing
});
});
please ..help me with this problem..thanks in advance..
When user connects - register on server side the time it happened.
Socket.IO has heart beating and pinging functionality. So just subscribe to disconnect event on server side and once it happens - means client disconnected - and you have on server time when client had connection. So that way you have timespan of client session.
Do not trust client to tell you any time or important data, as client can simply 'lie' - which leads to hacks/cheats/bugs on your server-side.
There is no reliable way to send data just before disconnect from client-side at all. There is nothing in Socket.IO for that, nor in just one of transports (WebSockets). As well as there is too many different scenarios of disconnection (power off, force close, ethernet cable out, wifi lose, etc).

Resources