我正在尝试编写一个简单的客户端/服务器实现,以使用 BinaryJS websockets 在浏览器和 node.js 服务器之间传输图像数据。
根据 api 示例,我想出了一些似乎有效的方法,但是随着“top”报告的 Node 进程的使用量不断增加,它似乎正在泄漏内存。
我不是很熟悉 javascript 调试,但使用 nodetime 在我看来好像创建的对象都没有被垃圾收集。
我的基本代码如下:
服务器:
var BinaryServer = require('binaryjs').BinaryServer;
var fs = require('fs');
var server = BinaryServer({port: 9000});
server.on('connection', function(client){
console.log('Connection');
client.on('stream', function(stream){
stream.on('data', function(data) {
var file = fs.createReadStream(data['path']);
client.send(file, {'target':data['target']});
});
});
});
客户:
var client = new BinaryClient('ws://example.com:9000');
var controlStream;
function loadImage(target, src) {
controlStream.write({'path':src, 'target':target});
}
client.on('open', function(){
controlStream = client.createStream();
});
client.on('stream', function(stream, meta){
var parts = [];
stream.on('data', function(data){
parts.push(data);
});
stream.on('end', function(){
$('#'+meta['target']+' img').attr('src', (window.URL || window.webkitURL).createObjectURL(new Blob(parts)));
});
});
我的理解是这样的:客户端打开一个到服务器的连接,然后创建一个流来发送请求。从该流接收数据后,服务器会打开一个具有请求路径的 FileStream,并通过新流将数据传输到客户端。完成后,客户端使用数据更新页面元素。
我在这里错过了什么?
最佳答案
这是 .createReadStream() 的一个已知(好吧,有点)问题;基本上,它不会自动释放资源。这是对您的脚本的修改,应该可以解决该问题:
var BinaryServer = require('binaryjs').BinaryServer;
var fs = require('fs');
var server = BinaryServer({port: 9000});
server.on('connection', function(client){
console.log('Connection');
client.on('stream', function(stream){
var file; //Moved this so it's accessible to the 'end' handler
stream.on('data', function(data) {
file = fs.createReadStream(data['path']);
client.send(file, {'target':data['target']});
});
stream.on('end', function(){
if (file) file.destroy.bind(file); //Releases the handle and allows garbage collection
});
client.on('close', function(){
if (file) file.destroy.bind(file); //Releases the handle and allows garbage collection
});
});
});
关于javascript - binaryjs websockets 泄漏内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25005958/