How to check consol.log and play sound in JavaScript - 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();
}
});

Related

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);
};

Websocket is not connecting with javascript

So i'm trying to connect to a websocket server using javascript. I tried doing this with NODEJS with the following code and it worked.
const WebSocket = require('ws');
const ws = new WebSocket('<Websocket Address>', {
origin: '<URL>'
});
ws.on('open', function open() {
ws.send(JSON.stringify({"event":"auth","args":["<My authentication token>"]}))
ws.send(JSON.stringify({"event":"send logs","args":[null]}))
console.log('connected');
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.addEventListener('send logs', function (event) {
console.log('Message from server ', event);
});
ws.on('message', function incoming(data) {
console.log(data);
}, 500);
Is there a way I can write this in plain javascript? Like in script tags? I've read that the following code should work but it's giving me this error Uncaught DOMException: "An invalid or illegal string was specified"
const ws = new WebSocket('<Websocket address>', {
origin: '<URL>'
});
ws.on('open', function open() {
ws.send(JSON.stringify({"event":"auth","args":["<My authentication Token>"]}))
ws.send(JSON.stringify({"event":"send logs","args":[null]}))
console.log('connected');
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.addEventListener('send logs', function (event) {
console.log('Message from server ', event);
});
ws.on('message', function incoming(data) {
console.log(data);
}, 500);
Could anyone tell me what i'm doing wrong?

Socket.io JS Client returning connection false

Im trying to connect the socket in my client js file but the response im getting is always false and no socket.on function is working
<script>
debugger
const socket = io.connect('http://localhost:5000');
console.log('check 1', socket.connected);
socket.on('connect', function () {
console.log('check 2', socket.connected);
});
socket.on("connect_error", (reason) => {
console.log('check 2', reason);
socket.connect();
});
socket.on('disconnect', function () {
console.log('check 2', socket.connected);
});
</script>
No function is running but looking at the network debugger it is returning 200 response . Any help would be apprecaited

websocket ping with node js

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,

How to disconnect and reconnect socket.io from client?

I have log messages that are being emitted from server to client and that are coming consistently from server and logging to client, Now I have additional functionality to stop and play logs to give some controls to user, So I am thinking on stop to disconnect socket.io connection and on play start socket.io connection again, First i am trying with stop to disconnect connection but i could not emit message to server ,any idea what is wrong with below code or any better solution to achieve these task ?
main.html
<button type="button" class="btn btn-success" ng-click="stopLogs()">stop</button>
ctrl.js
$scope.stopLogs = function(){
socket.emit('end');
}
angularSOcketFactory.js
angular.module('App').factory('socket', function ($rootScope) {
'use strict';
var socket = io.connect('http://localhost:3000');
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
server.js
var io = require('socket.io')(server);
io.sockets.on('connection',function(){
// Producer.startProducer();
ditconsumer.start(function(value){
io.emit('ditConsumer',value)
});
io.sockets.on('end', function() {
socket.disconnect();
console.log('it will disconnet connection');
});
});
This code is wrong:
io.sockets.on('end',function () {
console.log('this will disconnet socket connection');
io.sockets.disconnect();
});
You need to apply that event listener to one specific socket and then you need to disconnect one specific socket.
You don't show the general context of your server code, but it could be done like this:
io.on('connection', function(socket) {
socket.on('end', function() {
socket.disconnect();
});
});
You could also just have the client disconnect directly rather than asking the server to do it for you.

Categories

Resources