How to disconnect and reconnect socket.io from client? - javascript

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.

Related

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

Client-side event when Node server comes online

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

Agent to customer message transformation

I have two client sides like
1.Agent and customer
2.In Agent .I put a google cdn of socket
3.In customer also.I put a google cdn of socket
4.In Agent Transfers the messages from to nodejs server sends to customer
5.But the customer is out the website .
I write this code in node js server side
app.io.on('connection', function(socket) {
if(arraySockets.length<2){
arraySockets.push(socket);
if(arraySockets.length==1){
SocketAgent = arraySockets[0];
}
if(arraySockets.length==2){
SocketUser = arraySockets[0];
}
}
if(arraySockets.length==2) {
console.log("dffjdsg");
console.log(socket.id);
SocketUser.on('user', function (data) {
console.log(data);
var data = {
message: 'i am from server'
}
});
SocketAgent.on('agent', function (data) {
console.log(data);
var data = {
message: 'i am from server'
}
SocketUser.emit('outputuser',data);
});
}
});
Code on Agent side
services.js file in client Agent side:
schatApp.factory('socket', function ($rootScope) {
var socket = io.connect('http://localhost:8089/');
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);
}
});
});
}
};
});
controller side code in Agent side
schatApp.controller('homeController', function($scope,socket) {
socket.on('ouputuser',function(data){
alert(data);
});
$scope.Sendingmessage=function(){
var data={message:'hai simhachalam from agent'};
socket.emit('agent',data);
}
});
Client side code in customer side code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
</script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
$(document).ready(function(){
var socket = io.connect('http://localhost:8089/');
$("#sendmessage").click(function(){
var data={message:'iam from user'};
socket.emit('user',data);
});
});
</script>
</head>
<body>
<input type="button" id="sendmessage" value="submit">
</body>
</html>
I am receiving the messages from Agent to nodes server and customer to node server.
when I exchanging the messages socket object is overriding. So how can I solve the problem
socket.on('ouputuser',function(data){
alert(data);
});
data is not getting from the node js server

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!

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