websocket ping with node js - javascript

I am learning on how to use websockets. I am returning data to the front-end from the server via normal ws.send but I would at the same time I would like to have a set interval time to ping the front-end to see if clints are still alive there.. This is the code I am using at the moment.
ws.on('connection', function connection(ws, req) {
ws.on('message', function incoming(message) {
return_data = message;
heart_beat = {status:"Accepted", currentTime:"2013-02-01T20:53:32.486Z", "heartbeatInterval":300}
ws.send(JSON.stringify(heart_beat));
const interval = setInterval(function ping() {
ws.clients.forEach(function each(ws) {
if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false;
ws.ping('', false, true);
});
}, 300);
});
});
I want to just wait 300 seconds, if there is no response from the front-end I will terminate the websocket after the first heartbeat send by me
Here is my front-end code.
ws.onopen = function(){
console.log("Connected");
}
ws.onclose = function(){
console.log("Disconnected");
ws.send('Disconnected');
}
Whats happening now is that, when I close the browser in the front-end the server in the back-end is still pinging, if I console.log it.

You have to clear the Timeout with clearInterval
Here is a working example with uWebSocket :
'use strict';
const uws = require('uws');
const PORT = 3000
/*********************************************************************
* Server *
*********************************************************************/
var wsServer = new uws.Server({ 'port': PORT });
let nextId=1;
wsServer.on('connection', function(ws) {
console.log('connection !');
ws.id='cnx'+nextId++;
ws.on('message', function(mess){console.log('message : '+mess); });
ws.on('error', function(error) {
console.log('Cannot start server');
});
ws.on('close', function(code, message) {
console.log('Disconnection: ' + code + ', ' + message);
clearInterval(ws.timer);
});
ws.on('pong',function(mess) { console.log(ws.id+' receive a pong : '+mess); });
ws.timer=setInterval(function(){pingpong(ws);},1000);
});
function pingpong(ws) {
console.log(ws.id+' send a ping');
ws.ping('coucou',{},true);
} // end of pingpong
/*********************************************************************
* Client *
*********************************************************************/
var wsClient1 = createClient('client1');
var wsClient2 = createClient('client2');
function createClient(id) {
var client = new uws('ws://localhost:'+PORT);
client.id=id;
client.on('ping',function(mess){ console.log(this.id+' receive a ping : '+mess); } );
client.on('message',function(mess){ console.log(this.id+' receive a message : '+mess); } );
client.on('close',function(){ console.log(this.id+' closed'); } );
return client;
}
function closeClient(client) {
console.log('close '+client.id); client.close();
}
setTimeout(function(){ closeClient(wsClient1); closeClient(wsClient2); wsServer.close(); },2500);
output is :
connection !
connection !
cnx1 send a ping
cnx2 send a ping
client2 receive a ping : coucou
client1 receive a ping : coucou
cnx1 receive a pong : coucou
cnx2 receive a pong : coucou
cnx1 send a ping
cnx2 send a ping
client2 receive a ping : coucou
client1 receive a ping : coucou
cnx1 receive a pong : coucou
cnx2 receive a pong : coucou
close client1
close client2
client1 closed
client2 closed
Disconnection: 0,
Disconnection: 0,

Related

PAHO js more then one connection not possible?

I connect with PAHO Javascript to my mosquitto broker. If i connect with a second client, the first one will be disconnected. With the timeout of 2 Seconds the conetions wil be ping back and force, but can this be the reight solution?
var client = new Paho.MQTT.Client("192.168.5.100", 9880, "/", "mybro");
var reconnectTimeout = 2500;
function connectMqtt(){
console.log("connecting to mqtt ...");
try {
client.connect({
timeout: 3,
onSuccess: onConnect,
useSSL: false,
userName: "user",
password: "password",
keepAliveInterval: 30,
reconnect : false
});
} catch (error) {
console.log(error);
}
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
}
function onConnect() {
try {
client.subscribe("shellies/#");
client.subscribe("openWB/#");
console.log("Connected!");
} catch (error) {
console.log(error);
}
}
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
setTimeout(connectMqtt, reconnectTimeout);
}
}
function onMessageArrived(message) {
setDataToGui(message.destinationName, message.payloadString);
}
What did I try? Everything, what i have found in internet. There should be a problem in my code.
I need to connect with more then one Webbrowser (clients).
var client = new Paho.MQTT.Client("192.168.5.100", 9880, "/", "mybro");
The problem is the last entry in this function. It is the client ID that must be unique to EVERY client connecting to the broker.
You will need to generate the value most likely as a random number or a very high precision timestamp to limit the chances of 2 clients generating the sme value.

How to check consol.log and play sound in JavaScript

I am planning for queue system application using WebSocket ,PHP ,MySQL ,HTML to send console.log from one client to another to play sound for next queue ,
now I want to check in clinet2 if console.log value which I receive it client ='Hello From Client1!' paly sound or if = 'another message' do action.
Client1
<button onclick="sendMessage()">Send Msg</button>
</body>
<script>
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:3000');
// Connection opened
socket.addEventListener('open', function (event) {
console.log('Connected to WS Server')
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
const sendMessage = () => {
socket.send('Hello From Client1!');
}
</script>
Client2
<button onclick="sendMessage()">Send Msg</button>
</body>
<script>
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:3000');
// Connection opened
socket.addEventListener('open', function (event) {
console.log('Connected to WS Server')
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
const sendMessage = () => {
socket.send('Hello From Client2!');
}
</script>
Thanks All,
I think I got some code can help me.
I add in Client 1
<script>
var connection = new WebSocket ('ws://localhost:3000');
connection.onmessage = function (event){
document.getElementById("sul").value=event.data;
};
const sendMessage = () => {
socket.send("test");
}
</script>
<output type="text" id="sul" value="" readonly></output>
and client 2
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
if (event.data =='sul 1'){
console.log('Here i can put my play sound');
playsound();
}
});

React Websocket gets inactive after some time

I am using Azure Pub-Sub Service for Chatting module in a ReactApplication, I am creating this connection using Websocket.
let ws = new WebSocket(token.url);
ws.onmessage = (data) => {
//Messages Logic
}
when i am in other tabs, or in the sametab for longer time(more than 40-45 mins). I am not receiving messages, but when i refresh the page and websocket initialization code gets executed again and then i receive messages again. Any Suggestions?
Use this technique :
function connect() {
var ws = new WebSocket('ws://localhost:8080');
ws.onopen = function() {
// subscribe to some channels
ws.send(JSON.stringify({
//.... some message the I must send when I connect ....
}));
};
ws.onclose = function(e) {
console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
setTimeout(function() {
connect();
}, 1000);
};

PeerJS error when trying to call another peer: Failed to execute 'addStream' on 'RTCPeerConnection': parameter 1 is not of type 'MediaStream'

I am successfully establishing a connection between two peers using PeerJS but whenever I try passing a MediaStream object to the .call function I get this error:
Failed to execute 'addStream' on 'RTCPeerConnection': parameter 1 is
not of type 'MediaStream'
Everything else works great, connection is indeed established, both peers receive messages from each other via the 'open' event. The only thing that doesn't work is the peer.call() function. The microphone is properly captured after requesting the permission to do so.
Am I making some kind of a mistake here? I'd appreciate any help. Thank you.
Here is my code:
var media;
jQuery(document).ready(function() {
var peer = new Peer({
key: 'xxxxxxxxxxxxx'
});
media = navigator.mediaDevices.getUserMedia({
audio: true,
video: false
});
peer.on('open', function(id) {
console.log('My peer ID is: ' + id);
});
var conn = peer.connect(callID);
conn.on('open', function() {
// Receive messages
conn.on('data', function(data) {
console.log('Received', data);
});
// Send messages
conn.send('Hello!');
});
console.log(typeof(media));
var call = peer.call(callID, media);
peer.on('error', function(err) {
console.log(err);
});
});
I'd be interested to see the output of console.log(typeof(media));.
According to the MDN website, it seems that the following line will return a Promise instead of a MediaStream:
media = navigator.mediaDevices.getUserMedia({audio: true, video: false});
The following should work:
var media;
jQuery(document).ready(function() {
var peer = new Peer({
key: 'xxxxxxxxxxxxx'
});
navigator.mediaDevices.getUserMedia({
audio: true,
video: false
})
.then(function(mediaStream) {
peer.on('open', function(id) {
console.log('My peer ID is: ' + id);
});
var conn = peer.connect(callID);
conn.on('open', function() {
// Receive messages
conn.on('data', function(data) {
console.log('Received', data);
});
// Send messages
conn.send('Hello!');
});
console.log(typeof(media));
var call = peer.call(callID, mediaStream);
peer.on('error', function(err) {
console.log(err);
});
});
});

Send event to client, from server, and then disconnect the socket (from server)

I want to send an event back to a client, in Socket.io, and immediately after that to disconnect the client. The problem is that calling socket.emit() will not emit anything...
Do you know, or stepped into this kind of problem?
my code is like this:
- on server:
userCredentialsCheck: function (socket, next, callback) {
appLogSys.info('Check cookie!');
.....
var handshake = socket.request;
.....
parseCookie(handshake, null, function (err, data) {
sessionSrv.get(handshake, function (err, session) {
if (err) {
appLogSys.error(err.message);
next(new Error(err.message));
}
else
{
......
socket.emit('na', 'Error checking session! Good bye!');
socket.disconnect();
}
})
})
};
on client:
appSocket.on('na', function(d){
console.log('Error: '+d);
console.log('Now, redirect!');
//REDIRECT!
var delay = 1000; //Your delay in milliseconds
var URL = '/';
setTimeout(function(){ window.location = URL; }, delay);
});
Thank you!

Categories

Resources