Client-side event when Node server comes online - javascript

In my client-side node code, I have something like this:
var socket = io('//localhost:1337');
$(function() {
if ( !socket.connected )
NodeOfflineError();
});
Now, let's say I had a NodeBackOnlineAlert() function to go along with the NodeOfflineError() function, how would I know when to call it?
Is there a listener for the polling that checks whether the server is live?

You can have listeners that run the function and have a function to reconnect when the socket is disconnected:
socket.on("disconnect", function() {
NodeOfflineError();
socket.socket.reconnect();
});
socket.on("connect", function() {
NodeOnlineAlert()
});
socket.on("reconnect", function() {
NodeBackOnlineAlert()
});

You can use the listener events of socket io (assuming you use socket io)
const socket = io('//localhost:1337')
$(() => {
socket.on('connected', socket => {
console.log('connected!')
socket.on('disconnect', () => {
NodeOfflineError()
})
})
socket.on('reconnect', () => {
NodeBackOnlineAlert()
})
})
http://socket.io/docs/ Check the part where it says 'Sending and receiving events' also http://socket.io/docs/client-api/ :)

You could use Server Sent Events: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events. The MDN guide should have everything you need to implement them (they're quite simple!). This library might prove useful for your server: https://www.npmjs.com/package/sse

Related

Websocket is unable to reconnect after restarting the server in Javascript

I have a simple client-side script like this:
function connect() {
const { contextBridge } = require('electron');
var ws = new WebSocket('ws://localhost:3000');
ws.onerror = (error) => {
console.error(`Lost connection to server. Reason: ${error.message}`);
console.error('Attempting to reconnect...');
ws.close();
}
ws.onclose = (e) => {
setTimeout({
connect();
}, 500);
}
ws.addEventListener('open', () => {
console.log('Connected to server!');
});
// Some other stuff to call functions via the browser console
const API = {
ws_isOpen: () => { return ws.readyState === ws.OPEN }
}
contextBridge.exposeInMainWorld('api', API);
function send_msg(msg) {
// Process some data...
ws.send(msg);
}
}
connect();
It works normally when the server is running and it's trying to connect, or when the server is rebooting and it's trying to connect for the first time, but not while it's connected. What I mean is that, if I were to suddenly shut the server down while the client is being connected to it, it attempts to try to reconnect as usual and the success message does pop up. However, if I type in window.api.ws_isOpen() in the browser console, it returns false. When I try to send a message, an error pops up saying something like Websocket is already in CLOSING or CLOSED stage. I tried changing the ws variable type to let and const but it doesn't work.
Turns out the answer is really simple. For some reason, when I put the ws variable outside the connect() function and modify it in the function, it works. I'm guessing it kinda re-declares/re-new the ws variable. It looks something like this:
var ws = null;
function connect() {
ws = new WebSocket('ws://localhost:3000');
// the exact same as above here....
}
connect();
After rebooting the server and letting it reconnect:
>> window.api.ws_isOpen()
true
I feel like I'm supposed to know how this works...

SocketIO ReactJS - socket.io doesn't displays console.log()

I'm working on SocketIO with ReactJS vie a chat app.
When emitting message to my server my client doesn't receive the response of my server. The console.log controlling the mechanism is never displayed.
I can't figure out why since I follow exactly the SocketIO blueprint.
here my client.js :
send= (e) => {
e.preventDefault();
const socket= io.connect(this.state.endpoint);
socket.emit("message", () => {
message: "hey !"
})
console.log("send ended")
}
componentDidMount(){
const socket= io.connect(this.state.endpoint);
socket.on("new_message", (message) => {
console.log("new message ", message)
})
socket.on("user_connected", (message) => {
console.log(message)
})
}
here my server.js :
client.on("message", (message) => {
client.emit("new_message", message)
})
Any hint would be great,
Thanks
The reason for your problem is that you essentially have multiple instances of socket connections created over the life span of your client component.
From the server's perspective, the "new_message" is being emitted to the socket that you created in your components send arrow function. Because that socket instance does not listen to "new_message", you're therefore not going to see the expected log messages in the console.
Perhaps you could consider refactoring your client component code like this, to connect a single socket, and use that as a single means of sending and listening to messages from the server?
class YourComponent extends Component {
// Add socket field to component class
socket : ''
// Note that the send method is not an arrow function here, so
// care should be taken to consider how you invoke send() if
// your current implementation relies on this being an arrow function
function send(e) {
e.preventDefault();
const socket = this.state.socket // UPDATE: Access socket via state
// Send messages to server via the same socket instance of this class
if(socket) {
socket.emit("message", () => {
message: "hey !"
})
console.log("send ended")
}
}
function componentDidMount(){
const socket = io.connect(this.state.endpoint)
socket.on("new_message", (message) => {
console.log("new message ", message)
})
socket.on("user_connected", (message) => {
console.log(message)
})
// UPDATE: Connect the socket, and hold a reference for reuse by the component class
// instance via the component's state (seeing you can't add a class field for this)
this.setState({ socket : socket })
}
}

Node.js BinaryServer: Send a message to the client on stream end?

I'm using a node.js BinaryServer for streaming binary data and I want a callback event from the server, after the client calls for the .Stream.end() function.
I can't seem to understand - How can I send a message or some kind of notification when the node.js server actually closes the stream connection ?
Node JS:
server.on('connection', function(client) {
client.on('stream', function (stream, meta) {
stream.on('end', function () {
fileWriter.end();
// <--- I want to send an event to the client here
});
});
});
client JS:
client = new BinaryClient(nodeURL);
window.Stream = client.createStream({ metaData });
....
window.Stream.end();
// <--- I want to recieve the callback message
On the server side, you can send streams to the client with .send. You can send a variety of data types, but a simple string will probably suffice in this case.
On the client side you can also listen to the 'stream' event to receive data back from the server.
Node JS:
server.on('connection', function(client) {
client.on('stream', function (stream, meta) {
stream.on('end', function () {
fileWriter.end();
client.send('finished');
});
});
});
client JS:
client = new BinaryClient(nodeURL);
client.on('stream', data => {
console.log(data); // do something with data
});
window.Stream = client.createStream({ metaData });
....
window.Stream.end();

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.

Socket.io - Manual reconnect after client-side disconnect

I use node.js and socket.io to create a real time web application. I will give the users full control of the socket connection, like manual disconnect and (re)connect.
function socket_connect()
{
console.log('func socket_connect');
socket = io.connect('http://url/to/the/app');
}
function socket_reconnect()
{
console.log('func socket_reconnect');
socket_connect();
}
function socket_disconnect ()
{
console.log('func socket_disconnect');
if (socket) socket.disconnect();
}
On client start up the socket_connect() function works fine, but after using socket.disconnect(), no new connection starts.
You can reconnect by following client side config.
// for socket.io version 1.0
io.connect(SERVER_IP,{'forceNew':true });
It works now, with socket.socket.reconnect()
function socket_connect()
{
console.log('func socket_connect');
socket = io.connect('http://url/to/the/app');
}
function socket_reconnect()
{
console.log('func socket_reconnect');
socket.socket.reconnect();
}
function socket_disconnect ()
{
console.log('func socket_disconnect');
if (socket) socket.disconnect();
}
Related: https://github.com/LearnBoost/socket.io-client/issues/251
If you're using Socket.io 1.0, try using the io manager on the socket to handle manual disconnection and reconnection.
// Connect to socket.io
var socket = io.connect('url');
function manual_disconnect() {
socket.io.disconnect();
}
function manual_reconnect() {
socket.io.reconnect();
}
The reconnecting_attempt, reconnecting, reconnected and connected events on the socket should all be emitted afterwards.

Categories

Resources