简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM