第二次没有触发io连接事件

时间:2016-10-26 20:40:40

标签: javascript angularjs node.js socket.io

chokidar 模块的帮助下,我正在创建文件夹观察程序。我的Server.js代码是:

let express = require('express')
let app = express();
let http = require('http').Server(app);
let path = require('path');
let chokidar = require('chokidar');
let io = require('socket.io')(http);

let port = process.env.port || 1337;

let clientPath = path.join(__dirname, 'client');

app.use(express.static(clientPath));

app.get('/', function (req, res) {
    res.sendFile(path.join(clientPath, 'HTML1.html'));
});

http.listen(port, function () {
    console.log(`listning on ${port}`);
});

let watcher = chokidar.watch(path.join(clientPath, 'images'),
    { ignored: /^\./, persistent: true }
);

watcher
    .on('add', function (path) {
        console.log('File', path, 'has been added');
        io.sockets.on('connection', function (socket) {
            socket.emit('imageAddClient', { imagePath: path });
            socket.on('imageAddServer', function (data) {
                console.log(`${data.imagePath} has been processed at client`);
            });
        });
    })
    .on('change', function (path) {
        console.log('File', path, 'has been changed');
    })
    .on('unlink', function (path) {
        console.log('File', path, 'has been removed');
    })
    .on('error', function (error) {
        console.error('Error happened', error);
    });

在客户端,我已经创建角度工厂以在添加图像后自动加载页面。我的客户代码是:

var app = angular.module('imageLoaderApp', []);
app.controller('loadController', function ($scope, socket) {
    try {
        images = [];
        socket.on('imageAddClient', function (data) {
            let fileName = data.imagePath.substring(data.imagePath.lastIndexOf('\\') + 1);
            console.log(fileName);
            images.push({ name: fileName, src: fileName });
            socket.emit('imageAddServer', { imagePath: fileName });
        });

        $scope.images = images;
        //console.log($scope.images);
    }
    catch (exception) {
        console.log(`Error from loadController ${exception}`);
    }
});

app.factory('socket', function ($rootScope) {
    var socket = io.connect('http://localhost:1337');
    return {
        on: function (eventName, callBack) {
            socket.on(eventName, function () {
                let args = arguments;
                $rootScope.$apply(function () {
                    callBack.apply(socket, args);
                });
            });
        },
        emit: function (eventName, data, callBack) {
            socket.emit(eventName, data);
        }
    }
});

然而,'连接'来自io的事件仅被激活一次我启动服务器。如果我在文件夹中添加图像文件后,我可以看到观察者事件被触发,但' connection'事件未被解雇

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您需要在观察者之外声明io.on('connection')。您需要在启动时分配它,以便知道套接字何时连接。

var io = require('socket.io')(http);

io.on('connection', function(socket) {
	console.log('Socket connected!');

	socket.on('imageAddServer', function(data) {
		console.log('image has been processed at the client')
	});
	socket.on('disconnect', function() {
		console.log('Socket disconnected');
	});
});

watcher
    .on('add', function (path) {
        console.log('File', path, 'has been added');
		io.emit('imageAddClient', { imagePath: path }); //send it to the client sockets that are connected
    });

使用此代码作为更新代码的参考。

答案 1 :(得分:0)

实际上Murf让我走上正轨。我只是改变了他的序列。我在这里给出答案,以防将来有人需要它... 所以watcher和io的代码是这样的:

io.on('connection', function (socket) {
    executeWatcher(socket);
    socket.on('imageAddServer', function (data) {
        console.log(`${data.imagePath} has been processed at client`);
    });
    socket.on('disconnect', function () {
        console.log('Client disconnected');
    });

});

let executeWatcher = function (socket) {
    watcher
        .on('add', function (path) {
            console.log('File', path, 'has been added');
            socket.emit('imageAddClient', { imagePath: path });
        })
        .on('change', function (path) {
            console.log('File', path, 'has been changed');
        })
        .on('unlink', function (path) {
            console.log('File', path, 'has been removed');
        })
        .on('error', function (error) {
            console.error('Error happened', error);
        });
}