我正在编写一个Firefox扩展,我正在搜索与WebSocket(服务器在这里)传递压缩文件。客户端(发送文件)的代码如下:
var ws = new window.WebSocket("ws://localhost:12345");
function sendLogToOtherClient(file){
var zippedFileToSend = zipLogFile(file);
NetUtil.asyncFetch(zippedFileToSend, function(inputStream, status) {
if (!components.isSuccessCode(status)) {
return;
}
var bstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream);
bstream.setInputStream(inputStream);
var bytes = bstream.readByteArray(bstream.available());
bstream.close();
var encodedData = base64.encode(bytes, "utf-8");
ws.send(encodedData);
});
}
function zipLogFile(fileToZip){
var zippedFile = FileUtils.getFile("ProfD", ["report1.zip"], false);
var zipWriter = CCIN("@mozilla.org/zipwriter;1", "nsIZipWriter");
zipWriter.open(zippedFile, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE);
zipWriter.addEntryFile("logfile.txt", zipWriter.COMPRESSION_BEST, fileToZip, false);
zipWriter.close();
return zippedFile;
}
对于服务器端(接收文件并写入新的压缩文件):
server = new WebSocketServer(12345);
server.onclient = function(client) {
console.log(client + " connected");
client.onmessage = function(client, msg) {
client.send("Log Received");
var zippedTmpFile = FileUtils.getFile("ProfD", ["report2.zip"], false);
asyncTmpSave(zippedTmpFile, msg, onDone)
};
};
server.connect();
function asyncTmpSave(file, data, callbackDone){
var ostream = FileUtils.openFileOutputStream(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE);
var converter = CCIN('@mozilla.org/intl/scriptableunicodeconverter', "nsIScriptableUnicodeConverter");
converter.charset = 'UTF-8';
var istream = converter.convertToInputStream(data);
NetUtil.asyncCopy(istream, ostream, callbackSaved);
function callbackSaved (status) {
if(callbackDone){
if(status===0)callbackDone( file.path, file.leafName, status); //sucess.
else callbackDone( null, null, status); //failure.
};
}
}
function onDone(path, leafName, statusCode){
console.log([statusCode===0?"OK":"error",path,leafName].join("n"));
}
我试过传递字符串和通信工作,在这种情况下,数据被传递,文件被创建,但是。zip文件被损坏。你有什么主意吗?由于
你不能用utf-8编码随机的二进制内容。
WebSockets(和我的服务器)支持类型数组
所以当你发送愿望时:
var bytes = new Uint8Array(bstream.available());
bstream.readArrayBuffer(bytes.byteLength, bytes.buffer);
bstream.close();
ws.send(bytes);
在接收端,您也会收到一个Uint8Array
。